当向量上使用调整大小时,向量内部的结构中的unique_ptr不会编译

dsm*_*day 3 c++ vector unique-ptr visual-c++-2010 c++11

VS2010

我有一个unique_ptr内部结构.然后,我有一个vector这种结构.如果我尝试调整向量(或使用reserve),我会收到编译错误.下面是一个精简的例子,仍然存在问题.

struct Test
{
    unique_ptr<int> pValue;
};

void test()
{
    // this doesn't compile
    vector<Test> testVector;
    testVector.resize(5);

    // this also doesn't compile
    testVector.reserve(5);

    // this, of course, compiles
    vector<unique_ptr<int>> testVector2;
    testVector2.resize(5);
    testVector2.reserve(5);
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是关于访问unique_ptr(赋值运算符)的私有成员的投诉.编译器正在尝试动态构造Test &Test::operator =(const Test &)Test::Test(const Test &).我不明白为什么调整大小操作需要调用这些函数中的任何一个(为什么不调用默认构造函数,如果它需要?).他们都存在问题,因为它是不可能使要么unique_ptrconst.

How*_*ant 6

我讨厌打断你与自己的对话.:-)

但答案是VS2010尚未完全实现C++ 11规范(这需要一些时间旅行). Test应该有一个默认的noexcept移动构造函数来调用unique_ptr移动构造函数.VS2010没有实现这个隐式Test移动构造函数.如果是这样,您的完整示例将按预期编译并运行. vector将使用noexcept移动构造函数在需要时移动它.