unique_ptr列表的内容不可访问

Contents of list of unique_ptr are inaccessible

本文关键字:访问 ptr 列表 unique      更新时间:2023-10-16

我有一个std::unique_ptrsEntity对象的std::list。当我尝试这样循环它们时,程序说列表中的项是不可访问的。list是一个成员变量,声明为private:unique_ptr> .

void EntityContainer::E_Update(int delta)
{
    for (auto& child : children)
        child->Update(delta);
}

其中Update()为Entity的公共函数。但是,在编译时,我得到以下错误:

c:program files (x86)microsoft visual studio 11.0vcincludexmemory0(617): error C2248: 'std::unique_ptr<_Ty>::unique_ptr': cannot access private member in class 'std::unique_ptr<_Ty>'

您正在尝试复制unique_ptr。不能复制,只能移动。

第一种情况,使用引用:

for (auto const & child : children) {
    child->Update(delta);
}
在第二种情况下,直接使用解引用迭代器:
for (auto child = children.begin(); child != children.end(); ++child) {
   (*child)->Render();
}

或者,如果你真的需要一个单独的变量,让它成为一个引用:

unique_ptr<Entity> const & childPtr = *child;

我知道有一种新形式的基于范围的for循环的建议,它将通过引用访问元素:

for (child : children) {
    child->Update(delta);
}

但是官方还不存在