Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment operator and deep copy

Tags:

c++

I'm learning C++ and there is something I don't get about assignment operators. As far as I understand, they are supposed to provide deep copies of object. Here is an example

Test::Test(int i){
    value = i;
}

Test& Test::operator=(const Test& rhs){
    value = rhs.value;
    return *this;
}

Now:

Test* t1 = new Test(1);
Test* t2 = t1;  //t2 should be now a deep copy of t1
t1->value = 2;
cout << t1->value;
cout << t2->value;

Output is 22 but I expected '21'. What is the obvious thing I am missing here?

like image 575
znat Avatar asked Mar 23 '23 20:03

znat


1 Answers

Short answer

As Captain Obvlious suggests, call your assignment operator with

Test t2 = *t1

"Longer" answer

With this line

Test* t2 = t1

You are just making an assignment between pointers, so you are declaring a pointer to Test called t2 which will hold the same address held by the pointer t1.

When you modify the object using t1, you are actually changing the same object that also t2 is pointing to (this explains the output).

If you want to copy t1, you should use one of the following two ways:

Create a new Test object and copy construct it with t1:

Test t1;
Test t2(t1)

This code will call the copy constructor of the class Test:

Test::Test(const Test& t);

Use the assignment operator on an existing Test object:

Test t2;
t2 = t1;

As a general rule of thumb, when you need to define an operator=, then you probably need to define also a copy constructor and a destructor.

See the Rule of Three for more details.

like image 178
Vincenzo Pii Avatar answered Apr 09 '23 03:04

Vincenzo Pii