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.
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.
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.
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.
It can be assigned: class owner { std::unique_ptr<someObject> owned; public: owner() { owned=std::unique_ptr<someObject>(new someObject()); } };
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.
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
.
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