如何避免使用直接值初始化进行最烦人的解析 [英] How can I avoid most vexing parse with direct value initialization

查看:70
本文介绍了如何避免使用直接值初始化进行最烦人的解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读大多数令人讨厌的解析后,我了解以下代码也很含糊

After read Most vexing parse, I understand the following code is also ambigous

T x();

一方面,它可以解释为一个函数声明,该声明返回一个对象T;另一方面,它也可以解释为一个变量定义,并且对象x

In one hand, it can be interpreted as a function declaration which returns an object of T, on the other hand, it can also be interpreted as a variable definition, and object x is value-initialized.

我知道我可以像下面的代码一样使用统一初始化来避免冲突

I understand I can use uniform initialization like the following code to avoid confliction

T x{};

我还理解T是否是(C ++ 11之前的非POD)类,并且以下默认初始化实际上等于值初始化

I also understand if T is a (non-POD before C++11) class and the following default initialization actually equals value initialization

T x;

同时,如果不需要直接初始化,我们可以使用复制初始化

Meanwhile, if direct initialization is not necessary, we can use copy initialization

T x = T();

但是,我认为这三种解决方案中的任何一种都有其局限性.我知道是否有一些论点,我也可以使用一对额外的括号

Howerver, I think any of the three solutions are have their limitation. I know if there are some arguments, I can also use an extra pair of parentheses

T x((arg));

我想采用这种策略,但是以下代码不起作用

I want to adopt this strategy, but the following code does not work

T x(());

所以我想知道是否存在一些更好的直接值初始化解决方案?

So I am wondering is there are some better solutions with direct value initialization?

推荐答案

使用复制初始化,并依靠c ++ 17保证复制省略.

Use copy initialisation and rely on c++17's guarantee that copy elision will happen.

例如:

struct Foo
{
    Foo() = default;
    Foo(Foo const&) = delete;
};

int main()
{
    auto f = Foo();
}

https://godbolt.org/g/9tbkjZ

这篇关于如何避免使用直接值初始化进行最烦人的解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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