buttonsrtoys
buttonsrtoys

Reputation: 2771

Are move semantics implied immediately before an rvalue is destroyed?

In the following function:

void SetObject(Object object) 
{
    m_Object = object;
}

The SetObject would receive a copy of object, which is an rvalue that is assigned to m_Object and immediately goes out of scope.

Would move semantics be implied so that a second copy of object isn't created unnecessarily? Seems like move semantics should be implied, though I'm likely missing something. In other words, do I need to write this as follows?

void SetObject(Object object) 
{
    m_Object = std::move(object);
}

Upvotes: 0

Views: 48

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 596352

The object parameter of SetObject() may or may not have been initialized from an rvalue at the call site, but inside of SetObject() it is certainly not an rvalue, it is an lvalue (as it has a name).

As such:

void SetObject(Object object) 
{
    m_Object = object;
}

will perform a copy into m_Object, not a move.

You need to use std::move() explicitly to cast object into an rvalue in order to perform a move into m_Object (assuming Object supports move semantics, otherwise a copy will be performed):

void SetObject(Object object) 
{
    m_Object = std::move(object);
}

Upvotes: 1

eerorika
eerorika

Reputation: 238351

Yes, you do need std::move to avoid the copy.

Upvotes: 2

Related Questions