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

Question:

There is a class

class ArgClass {
public:
    ArgClass();
    ArgClass( const ArgClass& o );
    ArgClass& operator=( const ArgClass& o );
    ArgClass( ArgClass&& o );
    ArgClass& operator=( ArgClass&& o );
    ~ArgClass();
};

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.

Answer:

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