Uniform initialization in C++0x, when to use () instead of {}?

前端 未结 2 938
时光取名叫无心
时光取名叫无心 2021-02-13 13:17

Is there a rule of thumb to decide when to use the old syntax () instead of the new syntax {}?

To initialize

相关标签:
2条回答
  • 2021-02-13 13:47

    Take a look at this:

    http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=453&rll=1

    The use of a {}-style initializers on a variable has no direct mapping to the initialization lists on any constructors of the class. Those constructor initialization lists can be added/removed/modified without breaking existing callers.

    Basically the different behavior of the container is special, and requires special code in that container, specifically a constructor taking a std::initializer_list. For POD and simple objects, you can use {} and () interchangeably.

    0 讨论(0)
  • 2021-02-13 13:50

    I've found the answer in the standard docs(latest draft). Hopefully, I'll try to explain what I understood.

    First, if a class defines an initialization list constructor, then it is used whenever suitable:

    § 8.5.4 (page 203)

    Initializer-list constructors are favored over other constructors in list-initialization (13.3.1.7).

    I think this is a great feature to have, eliminating the headache associated with the non-uniform style :)

    Anyway, the only gotcha(which my question is about) is that if you design a class without the initializer constructor, then you add it later you may get surprising result.

    Basically, imagine std::vector didn't have the initializer list constructor, then the following would create a vector with 10 elements:

    std::vector<int> numbers{10};
    

    By adding the initializer list constructor, the compiler would favor it over the other constructor because of the {} syntax. This behavior would happen because the elements of the init-list {10} are accepted using the init-list constructor. If there is no acceptable conversion, any other constructor shall be used e.g.:

    std::vector<string> vec{10};
    // a vector of 10 elements.
    // the usual constructor got used because "{0}"
    // is not accepted as an init-list of type string.
    
    0 讨论(0)
提交回复
热议问题