When returning an object, why set creation + initialization and return as two separate statements instead of one?

Example:

Foo make_foo(int a1, int a2){
  Foo f(a1,a2);
  return f;
}

Having seen such functions several times, is it just a matter of coding style / preference, or is there something more than it seems at first glance? In particular, this answer made me think with implementation make_unique, and the requirement - a safe exception - is this related to the splitting of creation and return? Or am I reading too much about this? Why not just write

Foo make_foo(int a1, int a2){
  return Foo(a1,a2);
}
+3
source share
5 answers

Note that the answer you are referring to has something else:

std::unique_ptr<T> ret (new T(std::forward<Args>(args)...));

. , , , . . Boost shared_ptr Herb Sutter GotW, " " .

new , , , .


, , : "" .

, (RVO) . (NRVO) , RVO . , , ++.

+4

, , .

+7

, . , .

, , .

+4

, , , make_, class-template . , , , ++ 0x auto , , , , .

, .

0
source

Historically first version

Foo make_foo(int a1, int a2)
{
    Foo f(a1,a2);
    return f; 
} 

had a better chance of initiating NRVO optimization in some compilers (for example, the older MSVC).

Version 2 should work the same as for compilers that implement RVO , but historically it has not been so reliable.

0
source

All Articles