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?
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.
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 oftype f()whenfcreates the object. Those we want to change to the modern formtype 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:
Does that append or replace the vector?
And make caller code simpler:
vs.