防止不安全地取消引用std :: unique_ptr

德国Diago

摘自cppcon2015的一张幻灯片:

unique_ptr<A> f() {
   auto a = make_unique<A>();
   return a;
}

//Why does this even compile?
const A & dangling = *f(); 

//BOOM!!!
use(dangling);

我的问题是:使用* this的右值引用,可以解决这个问题吗?

我在cppreference的规范中看到:

typename std::add_lvalue_reference<T>::type operator*() const;

题:

  1. 禁止operator*rvalueunique_ptr并仅对lvalue unique_ptrs取消引用有效吗?
  2. 仍然有有效的用例来保持右值可取消unique_ptr引用?

像这样:

//Make sure it is an lvalue.
typename std::add_lvalue_reference<T>::type operator*() const &;

注意:我不确定语法或正确性,我对* this的右值引用没有经验。

皮特·斯科特尼克

我的问题是:使用的右值引用*this可以解决吗?

从技术上讲是。一种解决方案是为rvalue引入额外的(已删除)重载:

typename std::add_lvalue_reference<T>::type operator*() const&& = delete;
//                                                      ~~~~~~~~~~~~~~~^

并通过添加ref限定符来修改现有的:

typename std::add_lvalue_reference<T>::type operator*() const&;
//                                                         ~~^~~

由于右值强烈希望受右值引用约束,因此任何尝试取消引用涉及a的右值表达式的尝试unique_ptr都会导致编译错误-“使用已删除的函数”。

禁止operator*rvalueunique_ptrs只对lvalue有效的取消引用是否有意义unique_ptrs

不总是。因此,我怀疑该库是否应该对该unique_ptr规范施加其他约束,只是为了防止可能的滥用。

仍然有有效的用例来保持右值可取消unique_ptr引用?

临时项的生存期在该临时项所包含的完整表达式的结尾处结束。这意味着unique_ptr只要关联有效,从解引用a获得的对象就是有效的unique_ptr,因此以下用例是有效的,并且如果operator*禁用rvalues则不可能:

(*f()).foo();
//          ^~~ unique_ptr is destroyed here


use(*f());
//       ^~~ unique_ptr is destroyed here

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章