Why does this call the default constructor?

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?

2542 次浏览

括号是可选的,你说的和 X answer;是一样的,这是一个声明语句。

什么都没有,因为 X (答案) ; 可以被解释为变量的声明。

你的答案就藏在这里。如果声明一个变量,就调用它的默认 ctor (如果非 POD 等等)。

编辑: 要得到一个临时的,你有几个选择:

如果你想声明一个 X 类型的变量,你应该这样做:

X y(answer);