Member initializer list notation: curly braces vs parentheses

前端 未结 1 1818
迷失自我
迷失自我 2021-01-05 03:15

Consider the following code snippet from pg. 17 \'s A Tour of C++:

class Vector {
public:
  Vector(int s) :elem{new double[s]}, sz{s} { } //construct         


        
相关标签:
1条回答
  • 2021-01-05 03:45

    The form

    Vector(int s) :elem(new double[s]), sz(s) { }
    

    is correct in all versions of C++. The one with curly-braces, like

    Vector(int s) :elem{new double[s]}, sz{s} { }
    

    was introduced into the C++ standard in 2011, and is invalid in older standards.

    In the context you ask about, there is no difference. However, there are other language and library features, also introduced into the 2011 standard, that rely on the second form and don't work with the first.

    There are no other ways of initialising members of bases in initialiser lists of constructors. It is possible to assign to members in the body of constructors, but that is not initialiser syntax.

    0 讨论(0)
提交回复
热议问题