Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers arguments in copy constructor

Tags:

c++

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

like image 934
Ruchi Avatar asked Jun 21 '26 08:06

Ruchi


2 Answers

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.

like image 134
Björn Pollex Avatar answered Jun 23 '26 22:06

Björn Pollex


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);
like image 30
Martin York Avatar answered Jun 23 '26 21:06

Martin York



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!