【问题标题】:Why I can't move this vector in the copy constructor of my custom class?为什么我不能在我的自定义类的复制构造函数中移动这个向量?
【发布时间】: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&amp; test) 我认为const 不会让你move 它,如果你删除const 那么你应该看到你所期望的,但为什么copy ctor move 呢?
  • 谢谢!!!删除 const 后,它按我的预期工作。这只是一个测试,不适用于任何项目。谢谢

标签: c++ c++11 move-semantics move-constructor


【解决方案1】:

std::move 只是将传递给它的任何内容强制转换为 xvalue,因此 rvalue-references 可以绑定到它并可能窃取它的资源。这里:

TestClass(const TestClass& test):  p(std::move(test.p))

std::move 将产生一个const std::vector&lt;int&gt; &amp;&amp; 类型的表达式,如您所见,它有一个const 限定符。如果您在[vector] 上检查std::vector 的复制和移动构造函数,您会看到移动构造函数需要std::vector&lt;T&gt; &amp;&amp; 类型的表达式,而复制构造函数需要const std::vector&lt;T&gt; &amp;

vector(const vector& x);
vector(vector&&) noexcept;

std::move(test.p) 的结果与这两个构造函数进行比较。因为右值引用不绑定到具有const 限定符的类型(除非右值引用是const-qualified),所以移动构造函数重载不是一个好的选择。另一个候选者(复制构造函数)确实接受const-qualified 类型,并且由于 xvalues 具有与 rvalues 相同的属性:

http://en.cppreference.com/w/cpp/language/value_category#rvalue

右值可用于初始化 const 左值引用,在这种情况下,右值标识的对象的生命周期会延长,直到引用范围结束。

,复制构造函数是一个很好的候选者并被选中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 2012-04-29
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    相关资源
    最近更新 更多