I have the following code snippet.
#include <iostream>
using namespace std;
class A
{
int* ptr;
int size;
public:
A(int n):ptr(new int[n]),size(n)
{
cout << "default constructfor class A object:0x" << hex << this << dec << endl;
}
A(const A& obj): ptr (new int[obj.size]), size(obj.size)
{
memcpy (ptr, obj.ptr, obj.size);
cout << "copy constructfor class A object:0x" << hex << this << ", called with 0x" << &obj << dec << endl;
}
A operator=(const A& obj)
{
cout << "Normal assignment operator function called 0x" << hex << this << ", called with 0x" << &obj << dec << endl;
delete[]ptr;
ptr = new int[obj.size];
s
ize = obj.size;
memcpy(ptr, obj.ptr, obj.size);
return *this;
}
A(A&& obj) : ptr(obj.ptr), size(obj.size)
{
obj.ptr = NULL;
obj.size = 0;
cout << "move constructfor class A object:0x" << hex << this << ", called with 0x"<< &obj << dec << endl;
}
A& operator=(A&& obj)
{
cout << "move assignment operator function called 0x" << hex << this << ", called with 0x" << &obj << dec << endl;
ptr = obj.ptr;
size = obj.size;
obj.ptr = NULL;
obj.size = 0;
return *this;
}
~A()
{
cout << "destructor class A object:0x" << hex << this << dec << endl;
}
};
A f(A a) { return a; }
int main()
{
A a1(8);
A a2 = a1;
A a3 = *(new A(7)); // This would be a memory leak. please ignore this.
A a4 = f(a3);
a1 = a2 = a4 = f(a3) = a3;
cout << "Object a1 address - 0x" << hex << &a1 << dec << endl;
cout << "Object a2 address - 0x" << hex << &a2 << dec << endl;
cout << "Object a3 address - 0x" << hex << &a3 << dec << endl;
cout << "Object a4 address - 0x" << hex << &a4 << dec << endl;
return 0;
}
I want to understand the output for the following assignment statement.
a1 = a2 = a4 = f(a3) = a3;
The output which I get for this is as follows.
----------------------------------------------------------------------------
copy constructfor class A object:0x010FFB5C, called with 0x010FFCD4
move constructfor class A object:0x010FFBC4, called with 0x010FFB5C
destructor class A object:0x010FFB5C
Normal assignment operator function called 0x010FFBC4, called with 0x010FFCD4
copy constructfor class A object:0x010FFBB4, called with 0x010FFBC4
move assignment operator function called 0x010FFCC4, called with 0x010FFBB4
Normal assignment operator function called 0x010FFCE4, called with 0x010FFCC4
copy constructfor class A object:0x010FFBA4, called with 0x010FFCE4
move assignment operator function called 0x010FFCF4, called with 0x010FFBA4
----------------------------------------------------------------------------
Address of Object a1 - 0x010FFCF4
Address of Object a2 - 0x010FFCE4
Address of Object a3 - 0x010FFCD4
Address of Object a4 - 0x010FFCC4
Can someone please explain the output of the assignment statement in this code snippet? Please bear with me as I'm new to move and rvalue reference concepts.
Aucun commentaire:
Enregistrer un commentaire