Why can't variables defined in a conditional be constructed with arguments?

前端 未结 5 2079
星月不相逢
星月不相逢 2020-12-16 11:05

The question is simple. Why does this compile:

bool b(true);
if (b) { /* */ }

And this compile:

if (bool b = true) { /* */         


        
5条回答
  •  温柔的废话
    2020-12-16 12:03

    It's a bit technical. There's no reason why what you want couldn't be allowed, it just isn't. It's the grammar.

    An if statement is a selection statement, and it takes the grammatical form:

    if (condition) statement
    

    Here, condition can be either:

    • expression or
    • type-specifier-seq declarator = assignment-expression

    And there you have it. Allowing a declaration in a condition is a special case, and it must follow that form or your program is ill-formed. They could have probably allow direct-initialization instead of copy-initialization, but there isn't really any motivation to do so now. As Johannes Schaub points out, this change would break existing code, so it's pretty much never going to happen.

    Let_Me_Be notes that C++11 added a third form (I'm ignoring attributes here):

    decl-specifier-seq declarator braced-init-list
    

    So if (bool b{true}) is fine. (This can't possibly break any valid existing code.)


    Note your question seems to do with efficiency: don't worry. The compiler will elide the temporary value and just construct the left-hand side directly. This, however, requires your type be copyable (or movable in C++11).

提交回复
热议问题