Unique pointer in-class initialization

后端 未结 2 797
旧时难觅i
旧时难觅i 2020-12-11 05:26

Suppose I have a unique_ptr member object that I want to initialize in-class, see the code below. Why do I have to use uniform initialization (curly braces)? Th

2条回答
  •  囚心锁ツ
    2020-12-11 05:49

    Because those are the rules. In-class initialisers must use "braces" or "equals"; in fact, the syntactical element is called a brace-or-equal-initializer.

    int equals = 42;                      // OK
    std::unique_ptr braces{new Foo}; // Also OK
    

    I don't know why parentheses aren't allowed; perhaps to avoid the possibility of the initialisation looking like a function declaration. It can be annoying when there's a difference between direct and brace initialisation:

    std::vector bad(6);                     // ERROR: parentheses not allowed
    std::vector good{6};                    // OK but not the same
    std::vector ugly = std::vector(6); // OK but ugly
    

提交回复
热议问题