How can I avoid most vexing parse with direct value initialization

限于喜欢 提交于 2020-05-15 06:49:26

问题


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

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{};

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?


回答1:


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

eg:

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

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

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



来源:https://stackoverflow.com/questions/51707710/how-can-i-avoid-most-vexing-parse-with-direct-value-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!