Why does this call the default constructor?

随声附和 提交于 2019-12-17 08:04:14

问题


struct X
{
    X()    { std::cout << "X()\n";    }
    X(int) { std::cout << "X(int)\n"; }
};

const int answer = 42;

int main()
{
    X(answer);
}

I would have expected this to print either

  • X(int), because X(answer); could be interpreted as a cast from int to X, or
  • nothing at all, because X(answer); could be interpreted as the declaration of a variable.

However, it prints X(), and I have no idea why X(answer); would call the default constructor.

BONUS POINTS: What would I have to change to get a temporary instead of a variable declaration?


回答1:


nothing at all, because X(answer); could be interpreted as the declaration of a variable.

Your answer is hidden in here. If you declare a variable, you invoke its default ctor (if non-POD and all that stuff).

On your edit: To get a temporary, you have a few options:

  • (X(answer));
  • (X)answer;
  • static_cast<X>(answer)
  • X{answer}; (C++11)
  • []{ return X(answer); }(); (C++11, may incur copy)
  • void(), X(answer);
  • X((void(),answer));
  • true ? X(answer) : X();
  • if(X(answer), false){}
  • for(;X(answer), false;);
  • X(+answer);



回答2:


The parentheses are optional. What you said is identical to X answer;, and it's a declaration statement.




回答3:


If you want to declare a variable of the type X, you should do it this way:

X y(answer);


来源:https://stackoverflow.com/questions/11691021/why-does-this-call-the-default-constructor

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