Is there any way to call the move assignment operator in C++ without std::move?

Viewed 784

I wonder if it is possible to call the move assignment operator without using the standard library std::move.

So for example if I call :

class A {
    private:
        char* data;
    public:
        // move constructor
        A(A&& other) : data(other.data) {
            // we steal the pointer!
            other.data = NULL;
        }
        // move operator=
        A& operator=(A&& other) {
            if (this != &other) {
                delete data;
                data = other.data;
                data.foo = NULL;
        }
            return *this;
        }
};

int main(){
    A objA; 
    A objB; 
    objB = std::move(objA);
}


can I now write something other than objB = std::move(objA); ?

2 Answers

Is there any way to call the move assignment operator in C++ without std::move?

std::move is a very simple function that merely performs a cast. You can write that cast instead of calling the function:

objB = static_cast<A&&>(objA);

I don't know of a practical reason for doing this.

Assuming you want to keep objA as a named local variable then, no, there is no way to pass it to a constructor of objB and have the constructor being invoked be the move constructor, short of using std::move (or equivalent things that similarly return T&& to make the expression be an rvalue T, like a static_cast<A&&>).

That's by design. It should not be possible to accidentally move from a named, declared object; you should have to ask for it. That's why std::move is called std::move, despite not actually performing any move itself: its name strongly signals the usual intent of using it.

The other way to invoke a move constructor is to pass an expression that was never going to be an lvalue in the first place, such as one that creates a temporary.

Related