Search code examples
c++initializationcpp-core-guidelines

C++ Discussion: Use of =, {}, and () as initializers, Which one should I use?


While reading the C++ Core Guidelines by isocpp I came through this section. I have seen these methods in some of the C++ code I have read so far. For example: the () have been used while initializing data fields in the constructors initialization list even for primitive types while I also seen it being used locally. Some use the {} for initialization of variables. While others use this =. I don't know what is the difference between them. I mean do they achieve the same thing and are just different styles or they have different meanings. Can anyone explain!


Solution

  • You may be interested in a recorded talk about this subject - of the recent history of making uniform initialization "work" in C++ (11 and later):

    CppCon 2018: Nicolai Josuttis “The Nightmare of Initialization in C++”

    Some bits from the end of that talk:

    • Google, in their Abseil initiative, rejected trying to "convert" people to consistent use of curly-brace initialization. They therefore stick to adopting/recommending equals for "direct" initialization and parentheses when the initialization actively applies some logic. Nicolai disapproves of this approach.
    • Nicolai suggests: Make the effort to change our habits, and prefer curly-brace initialization. It is better now than it used to be.

    PS - This talk may also be of interest:

    Core C++ 2019 :: Timur Doumler :: Initialisation in modern C++

    it is more about surveying the intricacies of the different kinds of initialization (and there are quite a few!)