Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a C++ class doesn't own a pointer member?

Tags:

c++

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?

like image 404
user997112 Avatar asked Dec 01 '22 13:12

user997112


1 Answers

Future

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.


Present

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.

like image 168
TheOperator Avatar answered Dec 05 '22 06:12

TheOperator