Member initialization while using delegated constructor

大憨熊 提交于 2019-11-29 21:59:39

When you delegate the member initialization to another constructor, there is an assumption that the other constructor initializes the object completely, including all members (i.e. including the lines member in your example). You can't therefore initialize any of the members again.

The relevant quote from the Standard is (emphasis mine):

(§12.6.2/6) A mem-initializer-list can delegate to another constructor of the constructor’s class using any class-or-decltype that denotes the constructor’s class itself. If a mem-initializer-id designates the constructor’s class, it shall be the only mem-initializer; the constructor is a delegating constructor, and the constructor selected by the is the target constructor. [...]

You can work-around this by defining the version of the constructor that takes arguments first:

Tokenizer::Tokenizer(std::stringstream *lines)
  : lines(lines)
{
}

and then define the default constructor using delegation:

Tokenizer::Tokenizer()
  : Tokenizer(nullptr)
{
}

As a general rule, you should fully specify that version of the constructor that takes the largest number of arguments, and then delegate from the other versions (using the desired default values as arguments in the delegation).

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