dyesdyes
dyesdyes

Reputation: 1217

How to show that you pass ownership of the pointer

First, I know about unique_ptr and share_ptr, but I'm not using C++11 and thus I can't use them.

Every possible research from google returns a solution using those two smart pointers. I would like one without.

I need to pass ownership of a pointer to another class through the constructor.

PointerToPass* myPointer = new PointerToPass();
MyClass* myClass = new MyClass(myPointer);

So I could use raw pointers but I read everywhere that I should avoid it.

Using a reference is not an option.

I could use a smart pointer from Qt to show that I pass ownership like so:

QScopedPointer<PointerToPass> myPointer(new PointerToPass());
MyClass* myClass = new MyClass(myPointer.take());

This option clearly shows that the pointer is passed and that the ownership is given to myClass even if it's still using raw pointers.

Is there a better way to convey this idea?

It would be even better if it could be seen in the MyClass constructor signature.

Upvotes: 2

Views: 323

Answers (2)

Severin Pappadeux
Severin Pappadeux

Reputation: 20080

What about clear indication pointer is not to be used outside?

class myClass {
    public: myClass(PointerToPass*& p): _p(p) {
        p = nullptr;
    }

    public: ~myClass() {
        delete _p;
    }

    private: PointerToPass* _p;
};

PointerToPass* myPointer = new PointerToPass();

MyClass* myClass = new MyClass(myPointer);
std::cout << myPointer << "\n";

Upvotes: 3

user2093113
user2093113

Reputation: 3560

The C++ Core Guidelines has some advice about this and suggest you use owner from the Guideline Support Library (GSL) to annotate raw pointers.

template <class T>
using owner = T;

This is just a typedef of owner<T> to T. It serves only as annotation and would work for your constructor argument. If this syntax wasn't C++11.

We could use a similar idea instead though.

template<typename T>
struct owner
{
    typedef T pointer;
};

MyClass(owner<PointerToPass*>::pointer p)
{
    // ...
}

Similar to the technique in the guidelines, this doesn't actually enforce anything. It does annotate the code to make the ownership sematics clearer though.

Upvotes: 1

Related Questions