1

I am having difficulties understanding the ownership of unique pointers. Can anyone explain how it is possible to store a pointer to a unique pointer in a set?

Example from SFML game dev book which illustrates the problem:

typedef std::pair<SceneNode*, SceneNode*> Pair;

typedef std::unique_ptr<SceneNode> Ptr;

std::vector<Ptr> mChildren;

void SceneNode::checkSceneCollision(SceneNode& sceneGraph, std::set<Pair>& collisionPairs)
{
    checkNodeCollision(sceneGraph, collisionPairs);

    for(Ptr& child : sceneGraph.mChildren)
        checkSceneCollision(*child, collisionPairs);
}

void SceneNode::checkNodeCollision(SceneNode& node, std::set<Pair>& collisionPairs)
{
    if (this != &node && collision(*this, node))
        collisionPairs.insert(std::minmax(this, &node));

    for(Ptr& child : mChildren)
        child->checkNodeCollision(node, collisionPairs);
}

Does this not defy the meaning of a unique_ptr? Since it is possible to access the actual object from the set and modify it.

Tim Teige
  • 13
  • 2

2 Answers2

2

Does this not defy the meaning of a unique_ptr?

No. unique_ptr, as you’ve said, specifies ownership semantics – and nothing else. In particular, it specifies that there is only one owner of the pointer, but it does not say anything about access. There can be as many accessors as you want.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

The unique ptr is accesses only via reference. As such the ownersip in both cases never changes the container is the owner of ptr.

 for(Ptr& child : mChildren)
        child->checkNodeCollision(node, collisionPairs);

In this case for each contained pointer a reference is created the reference never invokes move or copy semantics therefor doesn't participate in the ownership.

rerun
  • 25,014
  • 6
  • 48
  • 78