I have a class with a pointer member, something like:
class MyClass
{
public:
void setPointer(Pointer* ptr){_pointer = ptr;}
private:
Pointer* _pointer{nullptr};
};
MyClass doesn't own the memory to _pointer. It just has a pointer to invoke methods it requires.
I started to write ~MyClass()
and I fortunately I realised it shouldn't delete _pointer
because it doesn't own it.
What is the best way to show MyClass doesn't have ownership of that pointer?
EDIT:
Should I use a unique_ptr in the owner class and a shared_ptr in MyClass, or should they both use shared_ptr?
At the moment, std::observer_ptr
is in discussion to express exactly those semantics: non-owning, passive pointers. See also this thread for its purpose.
In idiomatic C++ (latest since 2011), it's quite uncommon to still have raw pointers that own the object they're pointing to. The reason is that new
/delete
come with a lot of pitfalls, while there are better alternatives such as std::unique_ptr
and std::shared_ptr
. Those do not only bring the semantics needed, but also express the intent in code (unique or shared ownership, respectively).
Eventually it depends on code style of your environment, but I would say until a standard best-practice is established, T*
is a good convention for non-owning, passive pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With