Member initializer list notation: brackets vs parentheses

六眼飞鱼酱① 提交于 2020-01-11 08:45:12

问题


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 a Vector
  double& operator[](int i) { return elem[i]; } //element access: subscripting
  int size() { return sz; }
private:
  double* elem; // pointer to the elements
  int sz;  // the number of elements
};

Here I'm concerned about the member initializer list on the third line, where Stroustrup separates a colon from the two initializer statements elem{new double[s]} and sz{s}.

Question: Why here does he use brackets (i.e., {..}) to make these two initializer statements? I have seen elsewhere on the web people making initializer lists with parentheses, such that this could also (AFAIK) legally read elem(new double[s]) and sz(s). So is there a semantic difference between these two notations? Are there other ways one could initialize these variables (within the context of an initializer list)?


回答1:


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.



来源:https://stackoverflow.com/questions/36212837/member-initializer-list-notation-brackets-vs-parentheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!