samedi 25 avril 2020

Do I need to initialize with nullptr?

The other day I did a C ++ interview. I had to do code review...

This is not the example from interview but it is a good example of my question

class A{
    public:
    A(int n) : m_n{n}, m_v{new char[n]}{
    //do something
    }
    ~A(){
        if(m_v != nullptr)
        {
            //here I said it should be checked and initialized with nullptr
            delete []m_v;
            m_v = nullptr;
        }
    }
    private:
    int m_n;    
    char *m_v;

};

The interviewer said it was useless to do that. Nothing happens if you delete nullptr. I expected it to be undefined behavior. So my question Is a good practice to do that or not ? (or is it mandatory)

Aucun commentaire:

Enregistrer un commentaire