38

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<sf::Font>(font)}
    {
    }

I don't understand the syntax

m_font{..}

What is it? What does it do. I am sorry if this is really stupid question. I don't know what to Google, so asking here.

3
  • 4
    try googling: initializer list braces Commented Dec 18, 2016 at 19:44
  • Are you asking about the initializer brace list, or are you asking about the make_shared? Google shared pointers if the latter. Commented Dec 18, 2016 at 19:45
  • Here: stackoverflow.com/questions/24953658/… Commented Dec 18, 2016 at 19:47

3 Answers 3

24

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This begs the question: Why would you use braces instead of parenthesis for initialization?
@wingleader See this question.
And what would one put in the curly braces after initializing the variables?
9

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.

Comments

7

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.