Calling constructor with braces

后端 未结 2 1297
无人及你
无人及你 2020-12-03 15:23

Simple question about C++11 syntaxis. There is a sample code (reduced one from source)

struct Wanderer
{
  explicit Wanderer(std::vector

        
相关标签:
2条回答
  • 2020-12-03 15:37

    It is just C++11 syntax. You can initialize objects calling their constructor with curly braces. You just have to bear in mind that if the type has an initializer_list constructor, that one takes precedence.

    0 讨论(0)
  • It is neither initializer list, nor uniform initialization. What's the thing is this?

    Your premise is wrong. It is uniform initialization and, in Standardese terms, direct-brace-initialization.

    Unless a constructor accepting an std::initializer_list is present, using braces for constructing objects is equivalent to using parentheses.

    The advantage of using braces is that the syntax is immune to the Most Vexing Parse problem:

    struct Y { };
    
    struct X
    {
        X(Y) { }
    };
    
    // ...
    
    X x1(Y()); // MVP: Declares a function called x1 which returns
               // a value of type X and accepts a function that
               // takes no argument and returns a value of type Y.
    
    X x2{Y()}; // OK, constructs an object of type X called x2 and
               // provides a default-constructed temporary object 
               // of type Y in input to X's constructor.
    
    0 讨论(0)
提交回复
热议问题