Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

c++ - Why does this call the default constructor?

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...