The difference between them is really quite subtle. C ++ 11 introduced the initialization of a list of functions (also sometimes called initializing brackets):
Before C ++ 11, when you want to build a default construct and an o object of type Obj and build Position p from o , you had to write
Obj o; // default construct o Obj::Position p(o); // construct p using Position(Obj const&)
A common mistake for beginners (especially with the Java background) was to try to write this:
Obj o();
The first line declares a function , and the second tries to create a Position using a constructor that takes a pointer to a function as an argument. To have the same initializer syntax, C ++ 11 introduced list initialization:
Obj oo{}; // new in C++11: default construct o of type Obj Obj::Position p1(oo); // possible before (and after) C++11 Obj::Position p2{oo}; // new in C++11: construct p2 using Position(Obj const&)
This new syntax also works in return -statements, and this leads to the answer to your question: the difference between return {*this}; and return *this; the former initializes the return value directly from *this , while the latter first converts *this to a temporary Position object, and then initializes the return value indirectly from this temporary , which fails, because copy-and move-constructor have been explicitly deleted.
As previous posters noted, most compilers exclude these temporary objects because they are of no use; but this is only possible if they can be used in theory, because either an instance or a movement mechanism is available. Because this leads to a lot of confusion (why do I need parentheses around my return statement? Is the compiler giving a copy or not?), C ++ 17 eliminates these unnecessary time series and initializes the return value directly in both cases ( return {*this}; and return *this ).
You can try this using a compiler that supports C ++ 17. In clang 4.0 or gcc 7.1 you can pass --std=c++1z , and your code should be compiled with and without parentheses.
Tobias Aug 10 '17 at 21:13 2017-08-10 21:13
source share