Reputation: 6200
C++11 brings the new generalized initializers which can be nice. Question: Is any of the old syntax for initializing objects considered deprecated. In C++03 an object can be initialized as
Foo bar(x)
Foo bar=Foo(x)
Option (1) is preferred since it does not involve a copy. In C++11 there are more ways:
Foo bar{x}
auto bar=Foo{x}
With move constructors and assignment operators, option (4) should also be fine. Is (1) considered deprecated in favor of (3) or (4)?
Also, in C++03, the rule is that all constructors taking one argument should be explicit (except copy ctor). Other constructors are always explicit. With generalized initializers, any ctor can be implicit. Is the new rule then to put explicit everywhere, or just where the conversion would imply side effects (allocating a bunch of memory, creating a file...) or be lossy (double to float)?
Upvotes: 4
Views: 206
Reputation: 16935
Is (1) considered deprecated in favor of (3) or (4)?
Deprecated might not be the best choice of words. brace-initialization is preferred when possible. I mention this because Foo(x)
does not always correspond to Foo{x}
.
Consider the constructors for std::vector
:
std::vector<int> v1(10, 0); // Creates a vector of size 10 initialized with all 0's.
std::vector<int> v2{10, 0}; // Creates a vector with elements {10, 0}.
There's a difference in behavior between ctors; thus, it's not fair to say that (1) should be abandoned in lieu of (3) or (4).
This example sort of answers your second question:
Is the new rule then to put
explicit
everywhere ... ?
Yes. Because there would be an ambiguity, you don't want the compiler to attempt to resolve it - mark it as explicit
.
Upvotes: 3