Reputation: 15498
As far I understood, the proposed std::observer_ptr
is related to std::unique_ptr
in the same way as std::weak_ptr
is related to std::shared_ptr
.
So why does the std::observer_ptr<W>
interface, according to the proposal N4282, allow the construction from a W*
pointer?
This implies an implementation which contains a W*
as member, maybe similar to the pseudo-implementations given in this answer, which most simply proposes
template<typename T>
using observer_ptr = T*;
As a consequence, this seems to outrule validity checks as in the following:
std::unique_ptr<W> u = std::make_unique<W>();
std::observer_ptr<W> o(uptr.get());
uptr.reset();
if(o)
{
//u is already nullptr, but o doesn't know
o->foo(); //invalid dereferentation
}
Instead I would expect to only be allowed to do the following:
std::unique_ptr<W> u = std::make_unique<W>();
std::observer_ptr<W> o(uptr);
uptr.reset();
if(o)
{
//execution doesn't get here, o is nullptr
}
This is equivalent to what one can do with std::weak_ptr
by locking it, and is imo the central advantage observer_ptr
could offer over a non-owning raw pointer.
So, again, why isn't it enforced?
Upvotes: 0
Views: 351
Reputation: 227468
As far I understood the proposed
std::observer_ptr
is related tostd::unique_ptr
in the same way asstd::weak_ptr
is related tostd::shared_ptr
.
That is a misconception. It has no relation to unique_ptr
. It expresses that there is no connection to the ownership of the pointee.
Upvotes: 9