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

前端 未结 7 974

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 19:01

    This is my opinion.

    When using auto as type specifier, it's cleaner to use:

    auto q = p;   // Type of q is same as type of p
    auto r = {p}; // Type of r is std::initializer_list<...>
    

    When using explicit type specifier, it's better to use {} instead of ().

    int a{};   // Value initialized to 0
    int b();   // Declares a function (the most vexing parse)
    

    One could use

    int a = 0; // Value initialized to 0
    

    However, the form

    int a{};
    

    can be used to value initialize objects of user defined types too. E.g.

    struct Foo
    {
       int a;
       double b;
    };
    
    
    Foo f1 = 0;  // Not allowed.
    Foo f1{};    // Zero initialized.
    
    0 讨论(0)
提交回复
热议问题