Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointing to the content of std::unique_ptr

I have a std::unique_ptr and another raw pointer. I want the raw pointer to point to the content of the unique_ptr without any kind of ownership. It is read-only relationship:

auto bar=std::make_unique<foo>();
auto ptr=bar.get();// This may point to another value later

Is this bad? Is there any alternative?

Note: the real example is more complex. They are not in the same class.

like image 521
Humam Helfawi Avatar asked Aug 11 '16 16:08

Humam Helfawi


People also ask

Can you pass unique_ptr by value?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.

What is std :: unique_ptr?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

What does the get () function of the unique_ptr class do?

std::unique_ptr::getReturns the stored pointer. The stored pointer points to the object managed by the unique_ptr, if any, or to nullptr if the unique_ptr is empty.

Can unique_ptr be assigned?

It can be assigned: class owner { std::unique_ptr<someObject> owned; public: owner() { owned=std::unique_ptr<someObject>(new someObject()); } };


2 Answers

No, it's not bad, and until the standard library incorporates the proposed std::observer_ptr, it's the idiomatic way of expressing a non-owning observer.

like image 127
Angew is no longer proud of SO Avatar answered Sep 18 '22 17:09

Angew is no longer proud of SO


If you can guarantee that A) bar's lifetime will exceed the lifetime of ptr, AND B) that no programmer/refactoring will ever write delete ptr; at any point, then this is perfectly fine and is probably ideal for any situation where you need to pass pointers without ownership.

If those two conditions cannot be guaranteed, you should probably be using std::shared_ptr and std::weak_ptr.

like image 22
Xirema Avatar answered Sep 19 '22 17:09

Xirema