c++ – Why is copy being called instead of move?


There is a class

class ArgClass {
    ArgClass( const ArgClass& o );
    ArgClass& operator=( const ArgClass& o );
    ArgClass( ArgClass&& o );
    ArgClass& operator=( ArgClass&& o );

Template function:

template< typename Type >
void wrapper( Type&& param )
    ArgClass tmp;
    tmp = param;

Why the given code:

int main()
    ArgClass ac;
    wrapper( ArgClass() );

will call the copy constructor on the "tmp = param" line. The parameter to the wrapper function is of type ArgClass &&, and the move constructor must be called.


Because param inside the wrapper is a local variable, which means it has a name, an address … – in a word, it is an lvalue.

For it to be treated as an rvalue when passed to an rvalue function, you must use perfect forwarding forward :

tmp = std::forward<Type>(param);
Scroll to Top