Why this statement does not call the constructors - C++

早过忘川 提交于 2019-12-01 23:40:57

The statement Holder<Animal> a(Animal()); does not create a variable, but declares a function that returns a Holder<Animal> and that takes a function in parameter. It's usually called the most vexing parse, because of this ambiguity (that one would expect a variable rather than a function declaration).

Herb Sutter explains the different possible syntaxes here. In C++11, a possible solution is:

auto a = Holder<Animal> {};

You are victim to the "most vexing parse":

Holder<Animal> a(Animal()); is parsed as a function with name a, that returns a Holder<Animal> and takes as parameter another function, which has no parameters and returns an Animal.

In C++11 you can solve that problem by using uniform initialization:

Holder<Animal> a{Animal{}};

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