枚举unique_ptr的向量时编译错误

Compilation error enumerating vector of unique_ptr

本文关键字:编译 错误 向量 unique ptr 枚举      更新时间:2023-10-16
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;
    }
}

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

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

for(auto const& s : v)
//       ^^^^^^
{
    cout << s.get() << endl;
//          ^^^^^^^            
}

正如Andy Prowl指出的那样,unique_ptr是不可复制的(来自链接的参考页面):

unique_ptr既不是可复制的也不是可复制分配的

代码可以完全避免使用unique_ptr,只使用std::stringstd::to_string()代替:

void Test()
{
    std::vector< std::string > v;
    for(size_t i = 0; i < 5; ++i)
    {
        v.push_back( std::string("string ") + std::to_string(i) );
    }
    for(auto& s : v)
    {
        std::cout << s << std::endl;
    }
}