![](/img/trans.png)
[英]Why C++ lvalue objects can't be bound to rvalue references (&&)?
[英]C++: conversions of lvalue references and rvalue references
我想知道标准的哪些部分在以下代码段中指定:
#include <memory>
class A { };
class B : public A { };
int main()
{
std::unique_ptr<B> bptr = std::make_unique<B>(); // (a)
std::unique_ptr<A> aptr = std::move(bptr); // (b)
std::unique_ptr<A> &aptr_r = bptr; // (c)
std::unique_ptr<A> &&aptr_rr = std::move(bptr); // (d)
return 0;
}
(d)编制而且(c)没有编制。 请在答案中包含标准的相关部分或适当参考。 仅供参考, Ubuntu clang版本3.6.2-1(标签/ RELEASE_362 / final)(基于LLVM 3.6.2)给了我
error: non-const lvalue reference to type 'unique_ptr<A>' cannot
bind to a value of unrelated type 'unique_ptr<B>'
std::unique_ptr<A> &aptr_r = bptr;
^ ~~~~
和gcc(Ubuntu 5.2.1-22ubuntu2)5.2.1 20151010给了我
error: invalid initialization of reference of type ‘std::unique_ptr<A>&’
from expression of type ‘std::unique_ptr<B>’
std::unique_ptr<A> &aptr_r = bptr;
^
编辑:
为了使我的问题更清楚,让我补充一下
class C { };
std::unique_ptr<C> cptr = std::make_unique<C>(); // (e)
std::unique_ptr<A> &&aptr_rr2 = std::move(cptr); // (f)
什么是保持(f)编译时(d)? 显然A
和C
是无关的,但是当用于构造(d)和(f)的临时的std::unique_ptr
构造函数时检测到的是
template<class U, class E>
unique_ptr(unique_ptr<U, E> &&u);
您的案例之间的关键区别在于,右值引用可以间接(通过临时)绑定,而非const
值左侧引用则不能。 在(c)和(d)中,初始化程序不相似或可转换为[dcl.init.ref] /(5.1)中确定的类型,因此[dcl.init.ref] /(5.2)必须申请 - 立即排除(c):
否则,引用应是对非易失性
const
类型的左值引用(即, cv1应为const),或者引用应为右值引用。
另请注意, unique_ptr<A>
和unique_ptr<B>
是不同的,不相关的类型,无论A
和B
如何相关。
您也可以使用标量来观察该规则:
int&& i = 0.f; // Ok
int& i = 0.f; // Not ok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.