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

前端 未结 2 937
时光取名叫无心
时光取名叫无心 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: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 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 vec{10};
    // a vector of 10 elements.
    // the usual constructor got used because "{0}"
    // is not accepted as an init-list of type string.
    

提交回复
热议问题