Properly initialising variables in modern C++ (C++11 and above), using () or {}?

前端 未结 7 972

The C++ reference pages say that () is for value initialisation, {} is for value and aggregate and list initialisation. So, if I just want value initialisation, which one do

7条回答
  •  执笔经年
    2020-12-13 18:56

    Herb Sutter seems to be making an argument in CppCon 2014 (39:25 into the talk) for using auto and brace initializers, like so:

    auto x = MyType { initializers };
    

    whenever you want to coerce the type, for left-to-right consistency in definitions:

    • Type-deduced: auto x = getSomething()
    • Type-coerced: auto x = MyType { blah }
    • User-defined literals auto x = "Hello, world."s
    • Function declaration: auto f { some; commands; } -> MyType
    • Named Lambda: using auto f = [=]( { some; commands; } -> MyType
    • C++11-style typedef: using AnotherType = SomeTemplate

提交回复
热议问题