In modern C++ how should I manage unowned pointers?
I was thinking something like a weak_ptr
for unique_ptr
, but that doesn't seem to exist.
Example
For instance, if I have a class A
that owns a pointer, I should use unique_ptr<X>
instead of an old X*
pointer, e.g.
class A
{
std::unique_ptr<X> _myX;
};
But then if I have another class B
that uses this pointer, what do I do here? With C style pointers I would do this:
class B
{
X* _someX;
};
That seems correct, but it isn't obvious from the code that I've referenced another object's pointer (for instance a reader may think I could have just not used a smart pointer).
I have considered the following
std::shared_ptr<X>
- seems like a waste of reference counting becauseA
is guaranteed to outliveB
.std::weak_ptr<X>
- only works withshared_ptr
X&
- only works if X& is available in B's constructor
This seems like an obvious issue and sorry if it's been asked before. I've looked around and I have seen this question, but unfortunately the OP asked "is it OK to use X*" in one specific case. I'm looking for what I should generally be doing instead of X*, (if anything!).