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:
T(const T& cpy)
: m_var(cpy.m_var) // prefer initialization-list, thanks to @Loki Astari
{}
T* t1 = new T;
T* t2 = new T(*t1);
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 pointer t2 to the value of the pointer t1, 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.
The definition of a copy constructor requires a reference and is thus:
T(T const& copy) // This defines a copy constructor.
: m_var(copy.m_var) // Prefer to use the initializer list.
{}
So you need to pass a reference.
If you want to copy a pointer the usage is then:
T* t2 = new T(*t1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With