【发布时间】:2018-06-05 08:52:12
【问题描述】:
class TestClass
{
public:
TestClass(){
cout<<"constructor"<<endl;
p = {1,2,3};
cout<<(unsigned int *)(this->p.data())<<endl;
}
TestClass(const TestClass& test): p(std::move(test.p))
{
cout <<"copy constructor"<<endl;
cout<<(unsigned int *)(this->p.data())<<endl;
}
TestClass(TestClass && test): p(std::move(test.p))
{
cout <<"move constructor"<<endl;
cout<<(unsigned int *)(this->p.data())<<endl;
}
private:
std::vector<int> p;
};
int main()
{
TestClass t{};
TestClass p{t};
TestClass s{std::move(p)};
return 0;
}
输出是
constructor
0xb92bf0
copy constructor
0xb915b0
move constructor
0xb915b0
我只是想知道为什么构造函数下面的地址与复制构造函数下面的地址不同。据我了解,即使它是一个复制构造函数,但我使用 std::move 来获取一个右值引用,并且应该调用向量的移动构造函数,所以它们应该是同一个对象。
【问题讨论】:
-
移动需要修改源对象。
-
复制构造函数用于复制而不是移动,这就是移动构造函数的用途。当您像这样更改语义时,您会期望该类的复制构造函数应该如何工作。
-
TestClass(const TestClass& test)我认为const不会让你move它,如果你删除const那么你应该看到你所期望的,但为什么copy ctormove呢? -
谢谢!!!删除 const 后,它按我的预期工作。这只是一个测试,不适用于任何项目。谢谢
标签: c++ c++11 move-semantics move-constructor