How to implement a weak_ptr getter?

Viewed 489

I have a class (called Node) with a weak_ptr to an object that it doesn't own (called Level).

When implementing a getter for this pointer, should I just return the weak_ptr or a shared_ptr instead? One might argue that whether a class is using weak_ptr or not shouldn't concern the user of that class. And if I want to use the object in any way, I have to lock() it anyway, right? So I might as well just do that in the getter. Are there any problems with this?

class Node {
    std::weak_ptr<Level> _level;
public:
    const std::shared_ptr<Level> level() const { return _level.lock(); }
}

// somewhere else:

std::shared_ptr<Node> myNode;
// ...
auto level = myNode->level();
if (level) {
    // do stuff with level
}
0 Answers
Related