这个是我的代码, 按照移动构造函数的定义, 我先创建了一个对象 a, 这个对象强制使用 move 调用移动构造函数赋值给 b, 这个时候, a, b 里面的成员变量的地址 data 应该是一样的, 为什么我这里显示的不一样?
运行结果
Constructor is called for 10 000000950D2FF7F8 // addr Move Constructor for 10 000000950D2FF818 // addr Destructor is called for 10 Destructor is called for nullptr
// C++ program with declaring the
// move constructor
#include <iostream>
#include <vector>
using namespace std;
// Move Class
class Move {
public:
int* data;
// Constructor
Move(int d)
{
// Declare object in the heap
data = new int;
*data = d;
cout << "Constructor is called for "
<< d << endl;
};
// Copy Constructor
Move(const Move& source)
: Move{ *source.data }
{
// Copying the data by making
// deep copy
cout << "Copy Constructor is called -"
<< "Deep copy for "
<< *source.data
<< endl;
}
// Move Constructor
Move(Move&& source)
: data{ source.data }
{
cout << "Move Constructor for "
<< *source.data << endl;
source.data = nullptr;
}
// Destructor
~Move()
{
if (data != nullptr)
// If pointer is not pointing
// to nullptr
cout << "Destructor is called for "
<< *data << endl;
else
// If pointer is pointing
// to nullptr
cout << "Destructor is called"
<< " for nullptr "
<< endl;
// Free up the memory assigned to
// The data member of the object
delete data;
}
};
// Driver Code
int main()
{
// Vector of Move Class
//vector<Move> vec;
//// Inserting Object of Move Class
//vec.push_back(Move{ 10 });
//vec.push_back(Move{ 20 });
Move a(10);
cout << &(a.data) << endl;
Move b = move(a);
cout << &(b.data) << endl;
return 0;
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.