【问题标题】:Contents of list of unique_ptr are inaccessibleunique_ptr 列表的内容不可访问
【发布时间】:2014-08-04 04:43:41
【问题描述】:

我有一个 std::liststd::unique_ptrsEntity 对象。当我尝试循环遍历它们时,程序说列表中的项目不可访问。该列表是一个成员变量,声明为私有:list。

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

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

c:\program files (x86)\microsoft visual studio 11.0\vc\include\xmemory0(617):错误 C2248:'std::unique_ptr<_Ty>::unique_ptr':无法访问在类 'std::unique_ptr<_Ty>' 中声明的私有成员

【问题讨论】:

  • 尝试使用引用:unique_ptr<Entity>& child : children。您正在尝试复制 unique_ptrs。

标签: c++ list unique-ptr


【解决方案1】:

您正在尝试复制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);
}

但这还没有正式存在。

【讨论】:

  • 完美。非常感谢!该死的复制构造...我现在记得std库必须私下编写复制构造函数以避免客户端误用,因此出现不可访问性错误。干杯。
  • 嗯...没有完全工作。错误现在正在编译中。见上面的编辑。
  • @Tedium:看起来您仍在尝试复制指针。您确定将代码更改为使用引用吗?
  • 是的,我有。我将编辑原始帖子并删除错误代码以减少混乱。
猜你喜欢
  • 2012-08-29
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 2020-02-28
  • 2023-03-09
  • 1970-01-01
  • 2018-05-08
  • 2011-04-23
相关资源
最近更新 更多