dav*_*igh 0 c++ smart-pointers c++17
据我的理解,建议std::observer_ptr有关,std::unique_ptr如以同样的方式std::weak_ptr有关std::shared_ptr.
那么为什么std::observer_ptr<W>界面,根据提案N4282,允许从W*指针构造?
这意味着包含W*as成员的实现,可能类似于本答案中给出的伪实现,其最简单地提出
template<typename T>
using observer_ptr = T*;
Run Code Online (Sandbox Code Playgroud)
因此,这似乎超出了有效性检查,如下所示:
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
}
Run Code Online (Sandbox Code Playgroud)
相反,我希望只允许执行以下操作:
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
}
Run Code Online (Sandbox Code Playgroud)
这相当于std::weak_ptr通过锁定它可以做到的事情,并且imo observer_ptr可以提供超过非拥有原始指针的核心优势.
那么,为什么不执行呢?
据我所知,提议
std::observer_ptr与相关std::unique_ptr的方式std::weak_ptr有关std::shared_ptr.
这是一种误解.它与之无关unique_ptr.它表示与指针对象的所有权没有关联.