lsbbo lsbbo - 1 month ago 19
C++ Question

Move constructor used in aggregation initialization

I wonder if the following codes will obtain better performance

Obj obj;
obj.a = std::move(...);
...


compared to

Obj obj = {std::move(...), ...};


can compilers be able to do optimization on the codes above?

and which way do you prefer?

Answer

I tried on on http://godbolt.org/ a simple implementation of your code and found that in both cases the compiler was able to do optimization.

I'd prefer the first one if there is no performance difference, simply because initialization lists are overloaded too much. For instance let Obj be a class that has a constructor that takes two integers as arguments. You know std::vector< int > also has a constructor that takes two integers as arguments. But when give an initialization list {1, 3} to a vector< int >, the two-integer-argument constructor is NOT called! unlike in the Obj case.