【发布时间】:2015-12-20 09:35:21
【问题描述】:
取自 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;
问题:
- 禁止
operator*用于右值unique_ptrs 并且仅对左值unique_ptrs 有效的解引用有意义吗? - 仍有有效的用例可以保持右值
unique_ptr可取消引用?
像这样:
//Make sure it is an lvalue.
typename std::add_lvalue_reference<T>::type operator*() const &;
注意:我不确定语法或正确性,我对 *this 的右值引用没有经验。
【问题讨论】:
-
您的意思是
*f();而不是f();吗? -
顺便说一句。
const&仍然允许隐式对象是右值 -
auto non_dangling = f()怎么样来避免这个问题?真的是需要修复的指针吗? -
正确的规范应该没有 const 吗?我的要求有可能吗?
-
@BoPersson 问题更多是关于这是否可以避免,即使是愚蠢的。机器可执行。
标签: c++ c++11 c++14 unique-ptr