使用observer_ptr [英] Use of observer_ptr

查看:379
本文介绍了使用observer_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

构建点的确切点是 std :: observer_ptr >

What exactly is the point of the construct std::observer_ptr in the library fundamentals technical specification V2?

在我看来, / code>,如果它不添加动态内存安全,这似乎是一个多余的步骤。

It seems to me that all it does is wrap a bare T*, which seems like a superfluous step if it adds no dynamic memory safety.

在我的所有代码中,我使用 std :: unique_ptr 其中我需要明确拥有一个对象和< a href =http://en.cppreference.com/w/cpp/memory/shared_ptr> std :: shared_ptr 我可以共享所有权一个对象。

In all of my code I use std::unique_ptr where I need to take explicit ownership of an object and std::shared_ptr where I can share ownership of an object.

这非常好,可以防止对已经销毁的对象的意外解引用。

This works very well and prevents accidental dereferencing of an already destroyed object.

std :: observer_ptr 当然不能保证对象的生命周期。

std::observer_ptr makes no guarantee about the lifetime of the object observed, of course.

如果是从一个 std :: unique_ptr std :: shared_ptr 我会看到这样的结构中使用,只是使用 T * 可能只是要继续这样做,如果他们计划移动到任何东西,它将 std :: shared_ptr 和/或 std :: unique_ptr (取决于用途)。

If it were to be constructed from a std::unique_ptr or std::shared_ptr I would see a use in such a structure, but any code that is simply using T* is probably just going to keep doing so and if they plan on moving to anything it would be std::shared_ptr and/or std::unique_ptr (depending on use).

给定一个简单的示例函数:

Given a simple example function:

template<typename T>
auto func(std::observer_ptr<T> ptr){}

但是如果我想观察一个 std :: shared_ptr std :: unique_ptr 我必须写:

But if I want to observe a std::shared_ptr or std::unique_ptr I have to write:

auto main() -> int{
    auto uptr = std::make_unique<int>(5);
    auto sptr = std::make_shared<int>(6);
    func(uptr.get());
    func(sptr.get());
}

这使得它不安全:

template<typename T>
auto func(T *ptr){}






那么,这种新结构的用途是什么?

strong>

Is it just for self-documenting source?

推荐答案

proposal 非常清楚,它只是为了自我文档:

The proposal makes it pretty clear that it's just for self-documentation:


本文提出 observer_ptr ,一个(不是非常)智能指针类型,它没有所有权
责任,它的委任,即它观察到的对象。因此,它用作原始指针类型的接近
的替换,其优点是,作为词汇类型,它
表示它的预期用途,而不需要代码阅读器的详细分析。

This paper proposes observer_ptr, a (not very) smart pointer type that takes no ownership responsibility for its pointees, i.e., for the objects it observes. As such, it is intended as a near drop-in replacement for raw pointer types, with the advantage that, as a vocabulary type, it indicates its intended use without need for detailed analysis by code readers.

这篇关于使用observer_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆