Std :: move on the return value causes additional temporary creation of the object

Why does the call to get_data2 () lead to an additional call to c-tor (g ++ 4.7.1 -std = C ++ 11 -O3)?

code:

#include <iostream>

struct data {
    data(data&&){std::cout << "cted(&&): " << (void*) this << std::endl; }
    data(data const&){std::cout << "cted(c&): " << (void*) this << std::endl; }
    data(){std::cout << "cted(): " << (void*) this << std::endl; }
    ~data(){std::cout << "dted(): " << (void*) this << std::endl; }
};

data create_data() { return data(); }

// with this one the c-tor is called twice
data get_data2() { return std::move(create_data()); }

// with this one the c-tor is called once
data get_data1() { return create_data(); }
int main() { data var = get_data1(); return 0; }

Exit with get_data2 ():

cted(): 0x7ffffb2cd3df
cted(&&): 0x7ffffb2cd40f
dted(): 0x7ffffb2cd3df
dted(): 0x7ffffb2cd40f

Exit with get_data1 ():

cted(): 0x7ffffd7f230f
dted(): 0x7ffffd7f230f
+4
source share
1 answer

The problem is that explicit std::moveprohibits copying, see Why does std :: move prevent RVO? Another problem is that an explicit move is also not needed because data create_data() { return data(); }you are already returning an rvalue in.

: , , , , , , , . RVO .

: data create_data() { return data(); }.

+4

All Articles