缺少shared_ref [英] Missing shared_ref

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

问题描述

在使用 std :: shared_ptr 时,我很想念 shared_ref 的实现。这是 shared_ptr 的特化,它保证不会包装 nullptr (当然,要正确使用) 。
我有点想知道为什么它不在C ++ 11标准中。实施时有市长问题吗?

While working with std::shared_ptr a lot I kind of miss a shared_ref implementation. That is a specialization of shared_ptr, which guarantees, that it never wraps a nullptr (given right usage, of course). I kind of wonder why it is not in the C++11 standard. Are there any mayor problems when implementing it? On the top of my head I cannot think of any.

编辑:

我希望有一个界面类似于:

I would expect to have an interface similar to:

template <typename T>
class shared_ref {
public:
  shared_ref( T&& ref );
  T& get();
  T* operator&() const;

  template< class Y > 
  void reset( Y&& obj );

  long use_count() const;
  bool unique() const;

  void swap( shared_ref& r );
};


推荐答案


有市长吗实现时会出现问题?

Are there any mayor problems when implementing it?

这里是一个:您不能拥有引用的所有权。智能指针的全部目的是声明指针本身的所有权。 shared_ref 无法工作,因为您无法控制引用的生存期。

Here's one: you can't take ownership of a reference. The whole point of a smart pointer is to claim ownership of the pointer itself. shared_ref can't work because you can't control the lifetime of a reference.

而且不,这是也不会飞:

And no, this isn't going to fly either:

shared_ref( T&& ref ) : p(&ref) {}

用户可能已经给了你一个堆栈变量,这意味着你已经在这个对象和堆栈变量。堆栈变量不能与某物共享所有权。

The user may have given you a stack variable, which now means you have "shared" ownership between this object and a stack variable. And stack variables cannot share ownership with something.

您只能控制指针的生存期。并且指针可以为NULL。因此,您唯一可以做的就是运行时检查指针是否为NULL。

You can only control the lifetime of a pointer. And pointers can be NULL. Therefore, the only thing you can do is a runtime check to see if a pointer is NULL.

您可以做的绝对最好的事情是等于<$ c $的接口c> shared_ptr ,但它没有默认构造函数,并且在被赋予NULL的情况下抛出该异常。

The absolute best you can do is an interface equivalent to shared_ptr except that it has no default constructor and throws in the event of being given NULL. Is that really worth creating a whole new pointer type over?

C ++核心准则支持库具有 not_null 模板,该模板可以应用于大多数类似指针的类型。因此,当您要验证指针不是NULL时,可以使用 not_null< shared_ptr> ,但在指针进入使用状态时只能使用一次。最初创建指针后,不需要再次检查。

The C++ Core Guidelines support library has the not_null template, which can be applied to most pointer-like types. So you can use not_null<shared_ptr> when you want to verify that a pointer isn't NULL, but only once when it enters use. After the initial creating of the pointer, it doesn't need to check again.

当然,您不能强迫其他人使用它们,而是使用类型始终可以解决问题。

Granted, you can't force other people to use them, but use of the type consistently will resolve the issue.

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

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