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

Asked

Viewed 51 times

2

The builders move and copy are only called in the creation of an object? if yes, after the creation of an object, it is not possible to call either explicitly or implicitly the move or copy constructor of that object, right? The doubt arose 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 somehow the copy constructor was called after that, it would re-allocate memory in m_ptr and previously allocated memory would be leaked.

I am almost sure of the answer, but as I have never seen any explicit mention of it, I leave my doubt here.

1 answer

4


Yes, they’re still builders. After creating an object with it if you call the constructor it will create another object, each independent of the other. Or almost, the m_ ptr of each of them will probably point to the same object, at least certainly soon after the copy.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.