Copy and move constructors are called only in the creation of an object?

2

Are the move and copy constructors only called when creating an object? if yes, after the creation of an object, it is not possible to invoke either the move or copy constructor of that object, right? The doubt came from here:

class Engine
{
public:
    Engine(int length) : m_size(length), m_ptr(new int[length])
    {

    }

    ~Engine()
    {
        delete[] m_ptr;
    }

    Engine(const Engine& e) : m_ptr(new int[e.m_size])
    {
        this->m_size = e.m_size;
        *this->m_ptr = *e.m_ptr;
    }

private:
    int* m_ptr;
    int  m_size;
};

As we can see, when the constructor is called, it allocates space in the heap pro m_ptr . So if the copy constructor was somehow called after that, it would allocate memory again in m_ptr and the previously allocated memory would be leaked.

I'm almost sure of the answer, but since I've never seen any explicit mention of it, I leave my question here.

    
asked by anonymous 11.03.2018 / 13:09

1 answer

4

Yes, they do not stop being builders. Once you create an object with it if you call the constructor it will create another object, each independent of the other. Or almost, m_ ptr of each of them will probably point to the same object, at least certainly right after the copy.

In written form has a reasonable chance of having memory leak or even pointer loose, but nothing to do with the copy constructor itself, just with how the code inside it was written, could be in another method . Probably this code does not do what you expect and could be better written, but I do not know what the intention is.

    
11.03.2018 / 20:04