为什么这个片段不能在VS 2013中工作?

Why does this snippet not work in VS 2013?

本文关键字:2013 工作 VS 片段 不能 为什么      更新时间:2023-10-16

这段代码有什么问题吗?

#include <memory>
class Foo {
};
class Bar {
    std::unique_ptr<Foo> foo_;
};
int main() {
    Bar bar;
    Bar bar2 = std::move(bar);
}

我得到这个错误:

1>c:usersszxdocumentsvisual studio 2013projectsconsoleapplication1consoleapplication1main.cpp(13): error C2280: 'std::unique_ptr<Foo,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
1>          with
1>          [
1>              _Ty=Foo
1>          ]
1>          c:program files (x86)microsoft visual studio 12.0vcincludememory(1486) : see declaration of 'std::unique_ptr<Foo,std::default_delete<_Ty>>::unique_ptr'
1>          with
1>          [
1>              _Ty=Foo
1>          ]
1>          This diagnostic occurred in the compiler generated function 'Bar::Bar(const Bar &)'

但是GCC能够编译它而没有错误:http://ideone.com/CiDcGI

您的代码有效。VS2013拒绝它,因为编译器没有实现隐式生成move构造函数和move赋值操作符。注意,甚至不允许显式地默认它们。你唯一的选择是实现move构造函数。

class Bar {
    std::unique_ptr<Foo> foo_;
public:
    Bar(Bar&& b) : foo_(std::move(b.foo_)) {}
    Bar() = default;
};

来自MSDN:支持c++ 11特性(现代c++)

"右值引用v3.0"增加了在特定条件下自动生成移动构造函数和移动赋值操作符的新规则。然而,由于时间和资源的限制,这在Visual Studio 2013中的Visual c++中没有实现。