GP dreamtree
GP dreamtree

Reputation: 51

C++ lvalue and rvalue question.(move semantic)

Here is the code from the book

LargeType randomItem1( const vector<LargeType> & arr )
{
    return arr[ randomInt( 0, arr.size( )-1)]; 
}

const LargeType & randomItem2( const vector<LargeType> & arr ) 
{
    return arr[ randomInt( 0, arr.size( )-1)]; 
}
vector<LargeType> vec; 
...
LargeType item1 = randomItem1( vec );// copy 
LargeType item2 = randomItem2( vec );// copy
const LargeType & item3 = randomItem2( vec ); // no copy
vector<int> partialSum( const vector<int> & arr ) 
{
    vector<int> result( arr.size( ) ); 
    result[ 0 ] = arr[ 0 ];
    for( int i = 1; i < arr.size( ); ++i ) 
    {
        result[ i ] = result[ i-1]+ arr[ i ];
    } 
    return result;
}

vector<int> vec; 
...
vector<int> sums = partialSum( vec ); // Copy in old C++; move in C++11

The book says LargeType randomItem1( const vector<LargeType> & arr ) does not call move semantics while vector<int> partialSum( const vector<int> & arr ) does. Why is this happening? I understand that return arr[ randomInt( 0, arr.size( )-1)]; is an lvalue since arr itself is reference of object but isn't result an object too? the book says return result is temporary, however it is declared at line 3 at second code box.

want to know why return result is temporary even if it is declared and have name.

Upvotes: 1

Views: 88

Answers (2)

deezo
deezo

Reputation: 21

In addition to what NathanOliver said, vector<int> sums = partialSum( vec ); may result in neither copy nor move because of copy elision.

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180500

The fucntion randomItem1 does not own arr, which means it is not allowed to move arr[ randomInt( 0, arr.size( )-1)] out of the function.

In partialSum the function owns result so it is free to move it out of the function once the function ends.

The rule is that all function local variables can be treated as rvalues for the purpose of the return statement and only are considered an lvalue if no constructor can be found when considered as an rvalue.

Upvotes: 2

Related Questions