问题
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