0
class A
{
public:
    A()
    {
        cout << "A()" << endl;
    }

    A(const A&)
    {
        cout << "A(const A&)" << endl;
    }

    A(A&&)
    {
        cout << "A(A&&)" << endl;
    }

    A& operator=(const A&)
    {
        cout << "A(const A&)" << endl;
    }

    A& operator=(A&&)
    {
        cout << "A(const A&&)" << endl;
    }

    ~A()
    {
        cout << "~A()" << endl;
    }
};

A&& f_1()
{
    A a;
    return static_cast<A&&>(a);
}

A f_2()
{
    A a;
    return static_cast<A&&>(a);
}

int main()
{
    cout << "f_1:" << endl;
    f_1();
    cout << "f_2:" << endl;
    f_2();
}

the output is:

f_1:
A()
~A()
f_2:
A()
A(A&&)
~A()
~A()

The sample code obviously indicates that f_1() is more efficient than f_2().

So, my question is:

Should we always declare a function as some_return_type&& f(...); instead of some_return_type f(...); ?

If the answer to my question is true, then another question follows:

There have been many many functions declared as some_return_type f(...); in the C++ world, should we change them to the modern form?

BenMorel
  • 30,280
  • 40
  • 163
  • 285
xmllmx
  • 33,981
  • 13
  • 121
  • 269
  • 2
    Did you compile it with `-Wall`? "warning: reference to local variable ‘a’ returned". That's in your `f_1` definition... – mfontanini May 05 '12 at 16:06
  • http://stackoverflow.com/questions/4986673/c11-rvalues-and-move-semantics-confusion –  May 05 '12 at 16:08

2 Answers2

6

Is it a good practice that declaring a function as BigStruct&& foo(…);

Horrible practice. As with lvalue-references what you are doing is returning a reference to a local object. By the time the caller receives the reference the referred object is already gone.

There have been many many functions declared as some_return_type f(...); in the C++ world, should we change them to the modern form?

The modern form is the form in which they were already built (considering only return types). The standard was changed to make the common form more efficient, not to have everyone rewrite all their code.

Now there are non-modern versions out there, like void f( type& t ) instead of type f() when f creates the object. Those we want to change to the modern form type f() as that provides a simpler interface to reason about and provide for simpler user code:

Users don't need to think whether the object is modified or created:

void read_input( std::vector<int>& );

Does that append or replace the vector?

And make caller code simpler:

auto read_input();

vs.

std::vector<int> v; 
read_input(v);
BenMorel
  • 30,280
  • 40
  • 163
  • 285
David Rodríguez - dribeas
  • 192,922
  • 20
  • 275
  • 473
0

In f_2 you're preventing the compiler from applying NRVO. When you drop the cast, and compile with optimizations enabled, you'll find that it's just as efficient. There's absolutely no need for the cast-to-reference, it makes no sense in f_2.

Kuba hasn't forgotten Monica
  • 88,505
  • 13
  • 129
  • 275