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
是不可复制的。您应该使用对 const
的引用在基于范围的 for 循环中。此外,没有 operator <<
的重载对于 unique_ptr
, 和 unique_ptr
不能隐式转换为底层指针类型:
for(auto const& s : v)
// ^^^^^^
{
cout << s.get() << endl;
// ^^^^^^^
}
关于c++ - 枚举 unique_ptr vector 的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15198483/