Elliot Hatch
Elliot Hatch

Reputation: 1110

How should I retain a pointer to an std::unique_ptr?

I have a vector:

std::vector<std::unique_ptr<myClass>> vec;
//filling the vector
vec.push_back(std::unique_ptr<myClass>(new myClass()));
vec.push_back(std::unique_ptr<myClass>(new myClass()));
vec.push_back(std::unique_ptr<myClass>(new myClass()));

I need a handle to a specific instance of myClass that doesn't need to worry about ownership, e.g:

std::unique_ptr<myClass>& myInstance;

The problem is that myInstance will need point to different instances of myClass during runtime.

I know I could use an std::shared_ptr, but I want to keep them std::unique_ptr's so if something already initialized is added the ownership is transferred to vec.

How should I retain a pointer to an std::unique_ptr?

Additionally, would it considered bad practice to use a raw pointer here? The pointer won't need to manage any resources, but I don't want my code to get confusing.

Upvotes: 2

Views: 654

Answers (1)

Avi Berger
Avi Berger

Reputation: 2298

The comments to your post indicate that using a raw pointer in a "non-owning" capacity should be OK. I tend to concur with that general sentiment, but your case needs further examination.

For your situation you should not use "a pointer to an std::unique_ptr". The problem is that when you (or a maintenance programmer) adds to the vector, the vector could reallocate. If it does, your pointer is invalidated and must not be used.

One option would be to use the index into the vector instead of a pointer. This has the problem of breaking if you ever delete or rearrange entries in the vector.

Another, more robust, option is to use a pointer direct to the actual myClass object rather than the unique_ptr that owns it. This option is enabled by your use of a vector of unique_ptrs of objects instead of the more usual vector of objects.

Upvotes: 3

Related Questions