Humam Helfawi
Humam Helfawi

Reputation: 20264

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.

Upvotes: 16

Views: 3285

Answers (2)

Xirema
Xirema

Reputation: 20396

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.

Upvotes: 27

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.

Upvotes: 27

Related Questions