I have two objects as member variables of a class.

std::unique_ptr<Object> specificObject;
std::vector<std::unique_ptr<Object>> objects;

I know that specificObject will always be within objects. How can I point to specificObject without using shared_ptrs as I do not want the ownership of the objects in the container to be considered shared? Is this a case where a raw pointer can be used, or is shared_ptr really the solution?

1 Answer 1


In an ideal world, all owning pointers are smart pointers, and raw non-owning pointers are only used when NULL is considered a potentially valid value. If it is indeed true that specificObject will always be within objects, then at least in theory it should be possible to make specificObject be an Object reference, thereby allowing the compiler to enforce that it always has a non-NULL value for its entire lifetime.

In a less than ideal world, it might not be feasible or even possible to initialize specificObject to point to a member of objects, depending on how exactly specificObject is determined and whether that logic can reasonably be constexpr'd. Then the question comes down to whatever the lifetimes of all the Objects within objects are. If you know that they will all continue to exist at least as long as specificObjects does, then a non-owning raw pointer is perfectly safe. I suspect this is the most typical situation.

In a very non-ideal world, it may be possible for objects to gain and lose any of its members at any time, so you need to account for the possibility that specificObject gets invalidated while your program is still trying to do stuff with it. In this case, weak_ptr is the tool of choice, as it's specifically designed for situations where you don't know when the object's lifetime might end, yet you don't want to needlessly prolong it. Of course, that would require changing all your unique_ptrs to shared_ptrs, and unsurprisingly it is the least intuitive of the smart pointers, which is why I'm mentioning this option last.

  • Alas... objects will likely change constantly and the specific object being pointed to may vanish entirely. Am I doomed to have to use shared_ptrs forever??? It seems that anytime I start to use polymorphism and containers in C++ (which is always) I am forced to use shared_ptrs.
    – sydan
    Jan 7, 2016 at 20:01
  • @sydan If your objects have very unpredictable lifetimes and need to be used in multiple places, then yes, I can't imagine getting anything done without shared_ptrs or some equivalent thereof.
    – Ixrec
    Jan 7, 2016 at 20:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.