1

I've got a std::list of std::unique_ptrs to Entity objects. When I try to loop through them as such, the program says that the items within the list are inaccessible. The list is a member variable, declared as private: list< unique_ptr >.

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

Where Update() is a public function of Entity. However, upon compiling, I get the following error:

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>'

JordanBell
  • 140
  • 1
  • 2
  • 11

1 Answers1

4

You're trying to copy the unique_ptr. They can't be copied, only moved.

In the first case, use a reference:

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

In the second case, use the dereferenced iterator directly:

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

or, if you really want a separate variable, make it a reference:

unique_ptr<Entity> const & childPtr = *child;

I understand that there's a proposal for a new form of range-based for loop which will access the elements by reference:

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

but that doesn't officially exist yet.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Perfect. Thanks a lot! Damn copy construction... I remember now that the std library must have written the copy constructor privately to avoid client misuse, hence the inaccessibility errors. Cheers. – JordanBell Jun 13 '14 at 15:15
  • Hm... didn't work entirely. Error is now in compilation. See above edit. – JordanBell Jun 13 '14 at 15:30
  • @Tedium: It looks like you're still trying to copy a pointer. Are you sure you changed your code to use references? – Mike Seymour Jun 13 '14 at 15:45
  • Yeah, I have. I'll edit the original post and remove the bad code to reduce confusion. – JordanBell Jun 13 '14 at 15:50