Why does this call the default constructor?

后端 未结 3 1889
萌比男神i
萌比男神i 2020-11-30 19:00
struct X
{
    X()    { std::cout << \"X()\\n\";    }
    X(int) { std::cout << \"X(int)\\n\"; }
};

const int answer = 42;

int main()
{
    X(answer);
         


        
相关标签:
3条回答
  • 2020-11-30 19:35

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

    0 讨论(0)
  • 2020-11-30 19:47

    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);
    0 讨论(0)
  • 2020-11-30 19:48

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

    X y(answer);
    
    0 讨论(0)
提交回复
热议问题