[英]Why do we need a move constructor for vector of unique_ptr?
It seems that VC11 Update 2, requires a Move Constructor when pushing unique_ptr
's in an std::vector. 似乎VC11 Update 2在std :: vector中推送unique_ptr
时需要一个Move Constructor。 Is this a documented behavior or a known Bug? 这是记录在案的行为还是已知的Bug?
#include < iostream>
#include <memory>
#include <vector>
struct TEST
{
std::unique_ptr<int> m_l;
TEST(
std::unique_ptr<int>&& l)
{
m_l = std::move(l);
};
//Move Contructor for Test
TEST(TEST&& o)
{
m_l = std::move(o.m_l);
}
};
void Bar()
{
std::vector<TEST> vec;
std::unique_ptr<int> a(new int);
//Compiles fine without a Move Constructor
TEST(std::move(a));
//Requires a Move Contructor to compile
vec.push_back(
TEST(std::move(a)));
}
int main()
{
Bar();
return 0;
}
Note 注意
I tried the above code sans the Move Constructor on IDEONE C++11 and it compiles fine. 我尝试上面的代码没有在IDEONE C ++ 11上移动构造函数,它编译得很好。
You shouldn't have to write the move constructor yourself; 你不应该自己编写移动构造函数; it should be automatically generated by the compiler in this case. 在这种情况下,它应该由编译器自动生成。 However, VC11 doesn't implement this functionality and IIRC isn't going to be added until VS2013. 但是,VC11没有实现此功能,并且在VS2013之前不会添加IIRC。
Note that VC11 is complaining because the presence of a std::unique_ptr
data member causes your copy constructor to be deleted. 请注意,VC11正在抱怨,因为std::unique_ptr
数据成员的存在会导致复制构造函数被删除。 §12.8p11 describes this process of deleting a class's copy constructor: §12.8p11描述了删除类的复制构造函数的过程:
An implicitly-declared copy/move constructor is an inline public member of its class. 隐式声明的复制/移动构造函数是其类的内联公共成员。 A defaulted copy/move constructor for a class X is defined as deleted (8.4.3) if X has : 如果X具有以下内容, 则将类X的默认复制/移动构造函数定义为已删除(8.4.3) :
[...] [...]
— a non-static data member of class type M (or array thereof) that cannot be copied /moved because overload resolution (13.3), as applied to M's corresponding constructor, results in an ambiguity or a function that is deleted or inaccessible from the defaulted constructor, - 类型M (或其数组) 的非静态数据成员 ,由于应用于M的相应构造函数的重载解析(13.3), 无法复制 /移动,导致模糊或被删除或无法访问的函数默认构造函数,
[...] [...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.