Quick Q: What's the weak_ptr equivalent for unique_ptr? -- StackOverflow

Quick A: There isn't, because unique_ptr is unique. If you want shared ownership or shared observation, you need a shared_ptr. The "shared"-ness in shared_ptr enables both shared ownership (shared_ptr) and shared observation (weak_ptr).

shared_ptr<> is to weak_ptr<> as unique_ptr<> is to... what?

In C++11, you can use a shared_ptr<> to establish an ownership relation with an object or variable and weak_ptr<> to safely reference that object in a non-owned way.

You can also use unique_ptr<> to establish an ownership relation with an object or variable. But what if other, non-owning objects want to also reference that object? weak_ptr<> isn't helpful in this case. Raw pointers are helpful but bring various downsides (e.g. they can be automatically initialized to nullptr but this is accomplished through techniques that are not consistent with the std::*_ptr<> types).

What is the equivalent of weak_ptr<> for non-owning references to objects owned via unique_ptr<>?

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.