用括号召唤ctor

Loo*_*oom 9 c++ constructor c++11

关于C++ 11语法的简单问题.有一个示例代码(从代码减少一个)

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 {} ???
}
Run Code Online (Sandbox Code Playgroud)

我想知道,如何用大括号调用构造函数,Wanderer wanderer{update_loop};它既不是初始化列表,也不是统一初始化.这是什么东西?

And*_*owl 16

它既不是初始化列表,也不是统一初始化.这是什么东西?

你的前提是错的.它是统一初始化,在Standardese术语中,是直接括号初始化.

除非存在接受a的构造函数,否则std::initializer_list使用大括号构造对象等同于使用括号.

使用大括号的优点是语法不受令人烦恼的解析问题的影响:

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.
Run Code Online (Sandbox Code Playgroud)


jua*_*nza 5

它只是 C++11 语法。您可以使用花括号初始化调用其构造函数的对象。你只需要记住,如果类型有一个 initializer_list 构造函数,那个优先。