【问题标题】:Returning pointer by value does not move the object按值返回指针不会移动对象
【发布时间】:2012-11-28 18:25:01
【问题描述】:

我已经用 vs2011 编译了这段代码。它首先打印 constructor,然后打印 copy constructor。 但是,如果我将函数更改为返回 a 而不是 ap,它将移动对象。这是一个错误还是为什么会这样? *ap 不是右值吗?

struct A
{
  A() { cout << "constructor" << endl;}
  A(const A&) { cout << "copy constructor " << endl;}
  void operator=(const A&) { cout << "assignment operator" << endl; }
  A( A&&) { cout << "move copy constructor" << endl;}
  void operator=(A&&) { cout << "move assignment operator" << endl;}
};

A func() { A a; A *ap = &a; return *ap; }

int main()
{
    A a = func();
    return 0;
}

【问题讨论】:

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


    【解决方案1】:

    *ap 是一个左值(§ 5.3.1.1,n3290),对于自动发生的移动通常是不安全的。局部变量return a;different case。编译器不需要证明在这种特定情况下它是安全的。这是在您并不真正需要指针语义的情况下不使用指针的另一个很好的理由。

    改成:

    return std::move(*ap);
    

    但是会导致它被显式移动。

    【讨论】:

    • 一个xvalue!?突然之间,我感到非常的脱节。感谢您的链接。
    猜你喜欢
    • 2016-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多