枚举unique_ptr向量的编译错误

Ale*_*x F 3 c++ smart-pointers vector c++11

void Test()
{
    vector< unique_ptr<char[]>> v;

    for(size_t i = 0; i < 5; ++i)
    {
        char* p = new char[10];
        sprintf_s(p, 10, "string %d", i);
        v.push_back( unique_ptr<char[]>(p) );
    }

    for(auto s : v)                // error is here
    {
        cout << s << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'

And*_*owl 10

unique_ptr是不可复制的.您应该const在基于范围的for循环中使用引用.此外,没有operator <<for的重载unique_ptr,并且unique_ptr不能隐式转换为底层指针类型:

for(auto const& s : v)
//       ^^^^^^
{
    cout << s.get() << endl;
//          ^^^^^^^            
}
Run Code Online (Sandbox Code Playgroud)