Reputation: 3251
In the following code I have an object of class A
. I initiate its public member variable with the value of 0
. Then I call its method ReplaceThis
which executes command *this = A();
. Then I print the value and the address of the same object. The value is always some random gibberish while the address remains the same as before ReplaceThis
. This confuses me, because unchanged address indicates that the object has not moved in the memory, nevertheless the value changes into some random data even though the constructor of A
is empty.
If someone could explain what is going in this code step by step I would greatly appreciate it!
Code:
#include <iostream>
class A
{
public:
int Data;
A() {}
void ReplaceThis() { *this = A(); }
};
int main()
{
A foo;
foo.Data = 0;
std::cout << "Initial foo data: " << foo.Data << std::endl;
std::cout << "Initial foo address: " << &foo << std::endl;
foo.ReplaceThis();
std::cout << "Replaced foo data: " << foo.Data << std::endl;
std::cout << "Replaced foo address: " << &foo << std::endl;
}
Output:
Initial foo data: 0
Initial foo address: 0x7fff604594a0
Replaced foo data: 6296256
Replaced foo address: 0x7fff604594a0
Upvotes: 2
Views: 578
Reputation: 36438
We create the object:
A foo;
and set its Data
member:
foo.Data = 0;
then, in ReplaceThis()
:
*this = A();
means:
Data
will be junk)Data
Upvotes: 6
Reputation: 310980
In this statement
*this = A();
there is called implicitly defined by the compiler the copy or move assignment operator. It simply makes memberwise copy of the right hand object. Addresses of the objects are not changed.
Upvotes: 1