dynamic_cast 和右值引用
dynamic_cast and rvalue reference
class A{
public:
virtual ~A() {};
};
class B : public A{ };
int main(){
A&& p = B();
dynamic_cast<B&&>(std::move(p));
}
抛出错误(g++ 5.2.0):
error: conversion to non-const reference type 'std::remove_reference<A&>::type& {aka class A&}' from rvalue of type 'A' [-fpermissive]
它试图将 std::move(p)
强制转换为键入 A&
,但我不明白为什么。我认为有必要在转换为右值引用之前将 p
转换为右值,但如果我删除 std::move
它编译正常。来自 cppreference:
dynamic_cast < new_type > ( expression )
Similar to other cast expressions, the result is:
an lvalue if new_type is an lvalue reference type (expression must be an lvalue)
an xvalue if new_type is an rvalue reference type (expression may be lvalue or rvalue)
连N3337的5.2.7:
dynamic_cast<T>(v)
If T is a pointer type, v shall be a prvalue of a pointer to complete class type, and the result is a prvalue of type T. If T is an lvalue reference type, v shall be an lvalue of a complete class type, and the result is an lvalue of the type referred to by T. If T is an rvalue reference type, v shall be an expression having a complete class type, and the result is an xvalue of the type referred to by T.
唯一的要求是我使用完整的 class 类型,std::move(p)
是,不是吗?
这似乎有效:
B&& b = std::move(dynamic_cast<B&>(p));
不能告诉你为什么你的不正确。
您的代码当然没问题:
If T
is an rvalue reference type, v
shall be an expression having a
complete class type, and the result is an xvalue of the type referred
to by T
.
据推测,dynamic_cast
在引入右值引用时未正确更新,并且仍然执行 pre-C++11 规则,即右值只能绑定到 const
左值引用(请注意,将目标类型更改为 B const&&
时它甚至不起作用,尽管错误消息暗示了这一点!)。
归档为#69390。
class A{
public:
virtual ~A() {};
};
class B : public A{ };
int main(){
A&& p = B();
dynamic_cast<B&&>(std::move(p));
}
抛出错误(g++ 5.2.0):
error: conversion to non-const reference type 'std::remove_reference<A&>::type& {aka class A&}' from rvalue of type 'A' [-fpermissive]
它试图将 std::move(p)
强制转换为键入 A&
,但我不明白为什么。我认为有必要在转换为右值引用之前将 p
转换为右值,但如果我删除 std::move
它编译正常。来自 cppreference:
dynamic_cast < new_type > ( expression )
Similar to other cast expressions, the result is:
an lvalue if new_type is an lvalue reference type (expression must be an lvalue)
an xvalue if new_type is an rvalue reference type (expression may be lvalue or rvalue)
连N3337的5.2.7:
dynamic_cast<T>(v)
If T is a pointer type, v shall be a prvalue of a pointer to complete class type, and the result is a prvalue of type T. If T is an lvalue reference type, v shall be an lvalue of a complete class type, and the result is an lvalue of the type referred to by T. If T is an rvalue reference type, v shall be an expression having a complete class type, and the result is an xvalue of the type referred to by T.
唯一的要求是我使用完整的 class 类型,std::move(p)
是,不是吗?
这似乎有效:
B&& b = std::move(dynamic_cast<B&>(p));
不能告诉你为什么你的不正确。
您的代码当然没问题:
If
T
is an rvalue reference type,v
shall be an expression having a complete class type, and the result is an xvalue of the type referred to byT
.
据推测,dynamic_cast
在引入右值引用时未正确更新,并且仍然执行 pre-C++11 规则,即右值只能绑定到 const
左值引用(请注意,将目标类型更改为 B const&&
时它甚至不起作用,尽管错误消息暗示了这一点!)。
归档为#69390。