Unique pointer in-class initialization

后端 未结 2 798
旧时难觅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:45

    A non-static data member initializer (NSDMI) must use a brace-or-equal-initializer. The ( expression-list ) form of initialization isn't allowed.

    As N2756 explains, in order to allow NSDMIs to behave more like traditional constructor member initializer lists, the names inside initializers are looked up in the scope of the entire class. Unfortunately, this means that allowing parentheses initializers would make it impossible to determine whether something is an initializer or a function declaration at the time the declaration is parsed:

    // not real code
    struct X {
        int i(x);    // initializer
        static int x;
    };
    
    struct Y {
        int i(x);    // function
        typedef int x;
    };
    

    The paper discussed a couple possible ways to fix this short of banning it altogether ("everything that can be a declaration is a declaration" or "it's not a type unless you say it's a type"), but neither is very appealing, and the potential confusion was deemed to outweigh the benefit of allowing this form of initialization.

    0 讨论(0)
  • 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<Foo> 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<int> bad(6);                     // ERROR: parentheses not allowed
    std::vector<int> good{6};                    // OK but not the same
    std::vector<int> ugly = std::vector<int>(6); // OK but ugly
    
    0 讨论(0)
提交回复
热议问题