我有以下代码片段。
#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;
}
我想了解以下赋值语句的输出。
a1 = a2 = a4 = f(a3) = a3;
我为此得到的输出如下。
-------------------------------------------------- --------------------------
A 类对象的复制构造:0x010FFB5C,使用 0x010FFCD4 调用
A 类对象的移动构造:0x010FFBC4,使用 0x010FFB5C 调用
析构函数类A 对象:0x010FFB5C
称为 0x010FFBC4 的普通赋值运算符函数,使用 0x010FFCD4 调用
A 类的复制构造 对象:0x010FFBB4,使用 0x010FFBC4 调用
移动赋值运算符函数,调用 0x010FFCC4,使用 0x010FFBB4 调用
普通赋值运算符函数称为 0x010FFCE4,使用 0x010FFCC4 调用
A 类对象的复制构造:0x010FFBA4,用 0x010FFCE4 调用
移动赋值运算符函数调用 0x010FFCF4,调用 0x010FFBA4
---------------------------------------- ------------------------------------
对象 a1 的
地址 - 0x010FFCF4 对象 a2 的地址 - 0x010FFCE4
的地址对象 a3 - 0x010FFCD4
对象 a4 的地址 - 0x010FFCC4
有人可以解释这段代码片段中赋值语句的输出吗?请耐心等待,因为我是移动和右值参考概念的新手。