c++ - 枚举 unique_ptr vector 的编译错误

标签 c++ vector c++11 smart-pointers

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/

相关文章:

c++ - 相当于智能指针

c++ - 堆——构造函数和析构函数,内存分配

c++ - 当显式模板实例化定义先于显式声明时,GCC 和 clang 不同意

c++11 - cuda cpu 函数 - gpu 内核重叠

c++ - 为什么重载运算符时会出现编译错误而不是替换失败?

c++ - 使用 OpenGL 在程序的不同位置绘图

c++ - 类和结构可以在模板特化中互换使用吗?

C++ vector 调整大小元素重新排序?

c++ - 有人可以解释为什么这个 vector 删除操作不能正常工作吗?

c++ - 这是在 C++ 中实现有界缓冲区的正确方法吗