2014-06-13 140 views
1

我有std::liststd::unique_ptrsEntity对象。当我试图循环浏览它们时,程序会说列表中的项目是不可访问的。该列表是一个成员变量,声明为private:列表< unique_ptr>。unique_ptr列表的内容不可访问

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

其中Update()是实体的公共职能。然而,在编译时,我得到以下错误:

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

+3

尝试使用引用:'unique_ptr &child:children'。你正试图复制unique_ptrs。 – juanchopanza

回答

4

你试图复制unique_ptr。他们不能被复制,只能移动。

在第一种情况下,使用一个参考:

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

在第二种情况下,直接使用iterator的反引用:

for (auto child = children.begin(); child != children.end(); ++child) { 
    (*child)->Render(); 
} 

,或者,如果你真的想要一个独立的变量,使它参考:

unique_ptr<Entity> const & childPtr = *child; 

据我所知,有一个基于范围的新形式for循环,其将通过参考访问元件:

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

但是这还没有正式存在。

+0

完美。非常感谢!该死的复制建设...我记得现在std库必须已经写了私人复制构造函数,以避免客户端滥用,因此无法访问的错误。干杯。 – JordanBell

+0

嗯...没有完全工作。错误现在在编译中。见上面的编辑。 – JordanBell

+0

@Tedium:看起来你还在试图复制一个指针。你确定你改变了你的代码来使用引用吗? –