c++ - 用大括号调用构造函数

标签 c++ c++11 constructor

关于 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/

相关文章:

c++ - std::get_time 在 g++ 和 clang++ 中被破坏了吗?

javascript - 出错时撤消对构造函数范围的修改

c++ - 在C++ 11中是否有任何等于asm (“”::: “memory”)的编译器障碍?

C++ Quantlib 输出到控制台窗口

c++ - 无法调试 C++ 代码中的字符串转换

perl - 如何在我的父类中创建一个对象,但在 Perl 中将它祝福到我的子类中?

javascript - 访问对象内部键的值

android - 如何为每个项目构建关闭 C++ 编译器

c++ - 使用 decltype 的函数参数类型

c++ - 为什么我们总是检查输入是否失败而不是输出?