[英]Passing an rvalue to a function
I read a lot of information about rvalue links, I understood everything, but I met this example:我阅读了很多关于右值链接的信息,我什么都懂,但是我遇到了这个例子:
template<class T, class Arg>
T* make_raw_ptr(Arg &&arg)
{
return new T(arg);
};
If you pass rvalue to the make_raw_ptr
function without using the my_forward function, when using new T, there will be a copy constructor, not a move constructor.如果将右值传递给
make_raw_ptr
函数而不使用 my_forward 函数,则在使用 new T 时,将有一个复制构造函数,而不是移动构造函数。 I understand that arg
will be lvalue, despite the fact that it is an rvalue reference, but I have one question.我知道
arg
将是左值,尽管它是一个右值引用,但我有一个问题。 Why make a static_cast
arg
to an rvalue link when it is already an rvalue link, while using a static_cast<A&&>
to arg, the move constructor will be called?为什么在已经是右值链接时将
static_cast
arg
设置为右值链接,而在使用static_cast<A&&>
到 arg 时,将调用移动构造函数?
arg
itself is an expression that represents an object referred to by arg
and its value category is lvalue . arg
本身是一个表达式,表示由arg
引用的对象,其值类别是lvalue 。 It doesn't matter what the type of arg
actually is. arg
的类型实际上是什么并不重要。 A name of a variable / function parameter itself is always an lvalue expression.变量/函数参数本身的名称始终是左值表达式。
static_cast<A&&>(arg)
is an expression that represents the very same object as arg
, but its category is rvalue (and xvalue ). static_cast<A&&>(arg)
是表示与arg
完全相同的对象的表达式,但它的类别是rvalue (和xvalue )。 When you use this expression as the constructor argument, the move constructor will be preferred.当您将此表达式用作构造函数参数时,将首选移动构造函数。 The same effect is with
std::move(arg)
. std::move(arg)
也有同样的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.