用括号调用ctor [英] Calling ctor with braces

查看:152
本文介绍了用括号调用ctor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

使用大括号的优点是语法不受 Most Vexing Parse 问题:

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.

这篇关于用括号调用ctor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆