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. I understand that arg
will be lvalue, despite the fact that it is an rvalue reference, but I have one question. 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?
CodePudding user response:
arg
itself is an expression that represents an object referred to by arg
and its value category is lvalue. It doesn't matter what the type of arg
actually is. 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). When you use this expression as the constructor argument, the move constructor will be preferred. The same effect is with std::move(arg)
.