Вопрос

I am new to c++11 and have the following question while reading the C++11 FAQ.

Suppose we have a function f() that returns a value in type X, then we have the following ways to store its returned value:

X a = f();    // copy assignment
X&& b = f();  // move assignment

According to C++ FAQ, the second one avoids an unnecessary copy.

My question is: is the second one always the preferred way to receive the return value of a function call? In addition, is auto c = f(); equivalent to one of the above assignments? Thank you.

Это было полезно?

Решение

You have labelled the lines incorrectly. Neither of them are assignments, let alone copy and move assignments respectively. Instead, the first involves copy/move construction (depending on if X has a move constructor) and the second is simply initialising a reference.

The preferred way to receive the return value of a function call is the first way:

X a = f();

The copy from the temporary returned by f() into the object a will almost certainly be elided. This is the same form that auto c = f(); will take.

The second one should rarely, if ever, appear in your code. You are making an rvalue reference to the return type of f(). Stroustrup is only doing this to demonstrate that temporaries can bind to rvalue references. This occurs most often in real code when you invoke a move constructor/assignment operator, which have an rvalue reference argument type.

Другие советы

  1. None of what you wrote is an assignment. All code pieces declare and initialize a new variable.

  2. auto a = f() is the same as X a = f()

  3. X && b is a reference, not an object.

  4. Always create a local object variable, i.e. X a = f(), never an rvalue reference. There is (almost) never a good reason for the latter. In either case you get an object that lives for as long as the variable does, and there's no need for the additional complexity.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top