[英]Understanding the weird syntax with curly braces in a constructor initializer list
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.
我不知道谷歌该怎么做,所以在这里问。
This is described on cppreference , but in a somewhat hard to read format: 这是在cppreference上描述的,但格式有点难于理解:
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) (自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)
2)使用列表初始化来初始化由类或标识符命名的基或成员(如果列表为空,则变为值初始化,而在初始化集合时,则为集合初始化)
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
. 这是想说的是
X::X(...) : some_member{some_expressions} { ... }
导致some_member
类成员从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};
数据成员
y
将以与局部变量Y y{3};
完全相同的方式初始化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. 在您的情况下,
std::make_shared<sf::Font>(font)
会生成将用于初始化m_font
类成员的值。
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. 基本上,
m_font
变量是使用花括号中给出的值初始化的,在这种情况下,它被初始化为提供给构造函数的font
对象的shared_ptr
。
Font
类具有一个名为m_font
_ std::shared_ptr<sf::Font>
类型的m_font
成员,因此在Font
类的构造函数中,该成员正在使用共享的font
指针进行初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.