用大括号调用构造函数 [英] Calling constructor with braces
问题描述
关于C ++ 11语法的简单问题是。有一个示例代码(从源简化的代码)
Simple question about C++11 syntaxis. There is a sample code (reduced one from source)
struct Wanderer
{
explicit Wanderer(std::vector<std::function<void (float)>> & update_loop)
{
update_loop.emplace_back([this](float dt) { update(dt); });
}
void update(float dt);
};
int main()
{
std::vector<std::function<void (float)>> update_loop;
Wanderer wanderer{update_loop}; // why {} ???
}
我想知道,怎么可能在卷曲时调用构造函数方括号,例如 Wanderer wanderer {update_loop};
既不是初始化列表,也不是统一的初始化。这是什么意思?
I'd like to know, how it can be possible call constructor with curly brackets like Wanderer wanderer{update_loop};
It is neither initializer list, nor uniform initialization. What's the thing is this?
推荐答案
既不是初始化列表,也不是统一初始化。这是怎么回事?
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.
除非存在接受 std :: initializer_list
的构造函数,否则使用大括号构造对象等效于使用括号。
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.
这篇关于用大括号调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!