Understanding the weird syntax with curly braces in a constructor initializer list

后端 未结 3 997
情书的邮戳
情书的邮戳 2020-12-16 09:45

So I was just browsing the source code of a library when I encountered this.

Font::Font(const sf::Font& font) :
        m_font{std::make_shared

        
相关标签:
3条回答
  • 2020-12-16 09:47

    This is described on cppreference, but in a somewhat hard to read format:

    The body of a function definition of any constructor, before the opening brace of the compound statement, may include the member initializer list, whose syntax is the colon character :, followed by the comma-separated list of one or more member-initializers, each of which has the following syntax

    ...

    class-or-identifier brace-init-list (2) (since C++11)

    ...

    2) Initializes the base or member named by class-or-identifier using list-initialization (which becomes value-initialization if the list is empty and aggregate-initialization when initializing an aggregate)

    What this is trying to say is that X::X(...) : some_member{some_expressions} { ... } causes the some_member class member to be initialised from some_expressions. Given

    struct X {
        Y y;
        X() : y{3} {}
    };
    

    the data member y will be initialised the exact same way a local variable Y y{3}; would be initialised.

    In your case, std::make_shared<sf::Font>(font) produces the value that will be used to initialise the m_font class member.

    0 讨论(0)
  • 2020-12-16 09:54

    That is a list initialization aka brace initializer list. More specifically, in this case it's a direct-list initialization.

    Basically the m_font variable is initialized with the value that's given in the curly braces, in this case it's initialized to a shared_ptr for the font object that's given to the constructor.

    0 讨论(0)
  • 2020-12-16 10:09

    The class Font has a member called m_font of type std::shared_ptr<sf::Font>, so in the constructor of the class Font that member is being initialized with a shared pointer to font.

    0 讨论(0)
提交回复
热议问题