I have a problem where I want to clone of a object pointer when doing a deep copy.
like I have T* t1 and I want to create a new object pointer T* t2 in a way that *t1.x= *t2.x.
Is it a good Idea to write a copy constructor which will work like:
T(const T* cpy)
{
m_var = (*cpy).m_var;
}
T* t1 = new T;
T* t2(t1);
what things should I take care of if using the above approach?
Thanks
Ruchi
To do this you should write a normal copy-constructor and use it like this:
In the code you show,
T* t2(t1);would never call the constructor you have declared (which, by the way, is not a copy-constructor), because it simply initializes the pointert2to the value of the pointert1, making both point to the same object.As @Nawaz notes, this copy-constructor is equivalent to the one generated by the compiler, so you don’t actually need to write it. In fact, unless you have any manually managed resources (which, usually, you shouldn’t) you will always be fine with the compiler generated copy-constructor.