现在有observer_ptr的实现吗? [英] Is there an implementation for observer_ptr now?

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

问题描述

我想在我的项目中使用 observer_ptr ,但论文只定义了接口,而不是完整的实现。现在有没有开源实现,或者我自己做?

I'd like to use observer_ptr in my project, but the paper only defines the interface, not the complete implementation. Is there an open source implementation now, or I have to do it myself?

推荐答案

您可以创建所谓的 observer_ptr 通过使用NOP删除程序创建 unique_ptr ,轻而易举。

You can create the so called observer_ptr trivially by creating a unique_ptr with a NOP deleter.

template<typename T>
struct nop_deleter
{
  void operator()(T*) const {}
};

template<typename T>
using observer_ptr = unique_ptr<T, nop_deleter>;

这仍然会有 unique_ptr 的行为,这意味着它是move-only,而你想要 observer_ptr 是可复制的。这导致我们更简单的实现:

This will still have unique_ptr's behavior, meaning it's move-only, while you'd want observer_ptr to be copyable. Which leads us to a simpler implementation:

template<typename T>
using observer_ptr = T*;

这可以做到你想要的一切。你可以调用 observer_ptr< int> 而不是 int * ,因为后者是,邪恶。

This does everything you want. You can call it observer_ptr<int> instead of int *, because the latter is, of course, evil. It's copyable, and does nothing upon destruction.

我在上面的答案中提供了很好的表达,但是希望,将证明 observer_ptr 除了具有与原始指针类型不同的名称之外没有太多实用性。

I'm being facetious in the answer above, but hopefully, it'll demonstrate that observer_ptr doesn't have much utility other than having a different name than a raw pointer type. There's nothing wrong in using a non-owning raw pointer.

您可能会认为 observer_ptr 传达意图,但该参数仅在您的代码库包含管理资源的原始指针实例时有效。消除那些,然后一个原始指针将自动意味着 observer_ptr ...没有花哨的名称。

You may argue that observer_ptr conveys intent, but that argument is only valid if your code base contains instances of raw pointers that manage resources. Eliminate those and then a raw pointer will automatically mean observer_ptr ... without the fancy name.

如果你绝对必须有花哨的名称和/或不同的类型,自己实现它应该很容易。

If you absolutely must have the fancy name, and/or a distinct type, implementing it yourself should be easy.

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

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