The following code gives an error:
void EntityContainer::AddChild(Entity* child)
{
unique_ptr<Entity> childPtr(child);
children.push_back(childPtr);
}
I take it this may not be the correct way of creating a unique_ptr to an existing object. How could this be done properly? The above code gives the following error:
1>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>'
You cannot copy unique pointers. Because they are... unique. However, you can move them:
children.push_back(std::move(childPtr));
That's a bit redundant, so you could instead say:
children.push_back(std::unique_ptr<Entity>(child));
However, direct construction of container elements is already provided by the emplace
construction:
children.emplace_back(child);
None of this quite hits the mark, though. The problem is really that you have a function that silently takes ownership of something, and that is completely invisible in the interface. So really you should change the function signature and make the caller give you ownership explicitly:
void EntityContainer::AddChild(std::unique_ptr<Entity> child)
{
children.push_back(std::move(child));
}
Now it is no longer your fault if the user gets the ownership semantics wrong!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With