关于 C++11 语法的简单问题。有一个示例代码(从 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};
这样用大括号调用构造函数它既不是初始化列表,也不是统一初始化。这是什么东西?
最佳答案
It is neither initializer list, nor uniform initialization. What's the thing is this?
你的前提是错误的。它是统一初始化,用标准术语来说,就是直接大括号初始化。
除非存在接受 std::initializer_list
的构造函数,否则使用大括号构造对象等同于使用圆括号。
使用大括号的优点是语法不受Most Vexing Parse 的影响。问题:
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.
关于c++ - 用大括号调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15396124/