I've heard I can initialize a value using this syntax:
int foo = {5};
Also, I can do the same thing using even less code:
int foo{5};
Well, are there any advantages/disadvantages of using them? Is it a good practice, or maybe it's better to use standard: ?
int foo = 5;
The three examples you gave, are not quite the same. Uniform initialization (the ones with { }) does not allow narrowing conversions
int i = 5.0; // Fine, stores 5
int i{5.0}; // Won't compile!
int i = {5.0}; // Won't compile!
Furthermore, copy initializations (the ones with an =) do not allow explicit constructors.
The new C++11 feature uniform initialization and its cousin initializer-lists (which generalizes the brace initialization syntax to e.g. the standard containers) is a tricky animal with many quirks. The most vexing parse mentioned in the comments by #Praetorian is only one of them, tuples and multidimensional arrays are another pandora's box.
Related
The C++ reference pages say that () is for value initialisation, {} is for value and aggregate and list initialisation. So, if I just want value initialisation, which one do I use? () or {}? I'm asking because in the book "A Tour of C++" by Bjarne himself, he seems to prefer using {}, even for value initialisation (see for example pages 6 and 7), and so I thought it was good practice to always use {}, even for value initialisation. However, I've been badly bitten by the following bug recently. Consider the following code.
auto p = std::make_shared<int>(3);
auto q{ p };
auto r(p);
Now according to the compiler (Visual Studio 2013), q has type std::initializer_list<std::shared_ptr<int>>, which is not what I intended. What I actually intended for q is actually what r is, which is std::shared_ptr<int>. So in this case, I should not use {} for value initialisation, but use (). Given this, why does Bjarne in his book still seem to prefer to use {} for value initialisation? For example, he uses double d2{2.3} at the bottom of page 6.
To definitively answer my questions, when should I use () and when should I use {}? And is it a matter of syntax correctness or a matter of good programming practice?
Oh and uh, plain English if possible please.
EDIT:
It seems that I've slightly misunderstood value initialisation (see answers below). However the questions above still stands by and large.
Scott Meyers has a fair amount to say about the difference between the two methods of initialization in his book Effective Modern C++.
He summarizes both approaches like this:
Most developers end up choosing one kind of delimiter as a default, using
the other only when they have to. Braces-by-default folks are
attracted by their unrivaled breadth of applicability, their
prohibition of narrowing conversions, and their immunity to C++’s most
vexing parse. Such folks understand that in some cases (e.g., creation
of a std::vector with a given size and initial element value),
parentheses are required. On the other hand, the go-parentheses-go
crowd embraces parentheses as their default argument delimiter.
They’re attracted to its consistency with the C++98 syntactic
tradition, its avoidance of the auto-deduced-a-std::initializer_list
problem, and the knowledge that their object creation calls won’t be
inadvertently waylaid by std::initializer_list constructors. They
concede that sometimes only braces will do (e.g., when creating a
container with particular values). There’s no consensus that either
approach is better than the other, so my advice is to pick one and
apply it consistently.
This is my opinion.
When using auto as type specifier, it's cleaner to use:
auto q = p; // Type of q is same as type of p
auto r = {p}; // Type of r is std::initializer_list<...>
When using explicit type specifier, it's better to use {} instead of ().
int a{}; // Value initialized to 0
int b(); // Declares a function (the most vexing parse)
One could use
int a = 0; // Value initialized to 0
However, the form
int a{};
can be used to value initialize objects of user defined types too. E.g.
struct Foo
{
int a;
double b;
};
Foo f1 = 0; // Not allowed.
Foo f1{}; // Zero initialized.
First off, there seems to a terminology mixup. What you have is not value initialisation. Value initialisation happens when you do not provide any explicit initialisation arguments. int x; uses default initialisation, the value of x will be unspecified. int x{}; uses value initialisation, x will be 0. int x(); declares a function—that's why {} is preferred for value initialisation.
The code you've shown does not use value initialisation. With auto, the safest thing is to use copy initialisation:
auto q = p;
There is another important difference: The brace initializer requires that the given type can actually hold the given value. In other words, it forbids narrowing of the value, like rounding or truncation.
int a(2.3); // ok? a will hold the value 2, no error, maybe compiler warning
uint8_t c(256); // ok? the compiler should warn about something fishy going on
As compared to the brace initialization
int A{2.3}; // compiler error, because int can NOT hold a floating point value
double B{2.3}; // ok, double can hold this value
uint8_t C{256}; // compiler error, because 8bit is not wide enough for this number
Especially in generic programming with templates you should therefore use brace initialization to avoid nasty surprises when the underlying type does something unexpected to your input values.
{} is value initialization if empty, if not it is list/aggregate initialization.
From the draft, 7.1.6.4 auto specifier, 7/... Example,
auto x1 = { 1, 2 }; // decltype(x1) is std::initializer_list<int>
Rules are a little bit complex to explain here (even hard to read from the source!).
Herb Sutter seems to be making an argument in CppCon 2014 (39:25 into the talk) for using auto and brace initializers, like so:
auto x = MyType { initializers };
whenever you want to coerce the type, for left-to-right consistency in definitions:
Type-deduced: auto x = getSomething()
Type-coerced: auto x = MyType { blah }
User-defined literals auto x = "Hello, world."s
Function declaration: auto f { some; commands; } -> MyType
Named Lambda: using auto f = [=]( { some; commands; } -> MyType
C++11-style typedef: using AnotherType = SomeTemplate<MyTemplateArg>
Scott Mayers just posted a relevant blog entry Thoughts on the Vagaries of C++ Initialization. It seems that C++ still has a way to go before achieving a truly uniform initialization syntax.
MyClass a1 {a}; // clearer and less error-prone than the other three
MyClass a2 = {a};
MyClass a3 = a;
MyClass a4(a);
Why?
Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":
List initialization does not allow narrowing (§iso.8.5.4). That is:
An integer cannot be converted to another integer that cannot hold its value. For example, char
to int is allowed, but not int to char.
A floating-point value cannot be converted to another floating-point type that cannot hold its
value. For example, float to double is allowed, but not double to float.
A floating-point value cannot be converted to an integer type.
An integer value cannot be converted to a floating-point type.
Example:
void fun(double val, int val2) {
int x2 = val; // if val == 7.9, x2 becomes 7 (bad)
char c2 = val2; // if val2 == 1025, c2 becomes 1 (bad)
int x3 {val}; // error: possible truncation (good)
char c3 {val2}; // error: possible narrowing (good)
char c4 {24}; // OK: 24 can be represented exactly as a char (good)
char c5 {264}; // error (assuming 8-bit chars): 264 cannot be
// represented as a char (good)
int x4 {2.0}; // error: no double to int value conversion (good)
}
The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.
Example:
auto z1 {99}; // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99; // z3 is an int
Conclusion
Prefer {} initialization over alternatives unless you have a strong reason not to.
There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:
If the object I'm creating conceptually holds the values I'm passing in the constructor (e.g. containers, POD structs, atomics, smart pointers etc.), then I'm using the braces.
If the constructor resembles a normal function call (it performs some more or less complex operations that are parametrized by the arguments) then I'm using the normal function call syntax.
For default initialization I always use curly braces.
For one, that way I'm always sure that the object gets initialized irrespective of whether it e.g. is a "real" class with a default constructor that would get called anyway or a builtin / POD type. Second it is - in most cases - consistent with the first rule, as a default initialized object often represents an "empty" object.
In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).
It e.g. fits nicely with standard library-types like std::vector:
vector<int> a{10, 20}; //Curly braces -> fills the vector with the arguments
vector<int> b(10, 20); //Parentheses -> uses arguments to parametrize some functionality,
vector<int> c(it1, it2); //like filling the vector with 10 integers or copying a range.
vector<int> d{}; //empty braces -> default constructs vector, which is equivalent
//to a vector that is filled with zero elements
There are MANY reasons to use brace initialization, but you should be aware that the initializer_list<> constructor is preferred to the other constructors, the exception being the default-constructor. This leads to problems with constructors and templates where the type T constructor can be either an initializer list or a plain old ctor.
struct Foo {
Foo() {}
Foo(std::initializer_list<Foo>) {
std::cout << "initializer list" << std::endl;
}
Foo(const Foo&) {
std::cout << "copy ctor" << std::endl;
}
};
int main() {
Foo a;
Foo b(a); // copy ctor
Foo c{a}; // copy ctor (init. list element) + initializer list!!!
}
Assuming you don't encounter such classes there is little reason not to use the intializer list.
Update (2022-02-11):
Note that there are more recent opinions on that subject to the one originally posted (below), which argue against the preference of the {} initializer, such as Arthur Dwyer in his blog post on The Knightmare of Initialization in C++.
Original Answer:
Read Herb Sutter's (updated) GotW #1.
This explains in detail the difference between these, and a few more options, along with several gotchas that are relevant for distinguishing the behavior of the different options.
The gist/copied from section 4:
When should you use ( ) vs. { } syntax to initialize objects? Why?
Here’s the simple guideline:
Guideline: Prefer to use initialization with { }, such as vector
v = { 1, 2, 3, 4 }; or auto v = vector{ 1, 2, 3, 4 };, because
it’s more consistent, more correct, and avoids having to know about
old-style pitfalls at all. In single-argument cases where you prefer
to see only the = sign, such as int i = 42; and auto x = anything;
omitting the braces is fine. …
That covers the vast majority of cases. There is only one main
exception:
… In rare cases, such as vector v(10,20); or auto v =
vector(10,20);, use initialization with ( ) to explicitly call a
constructor that is otherwise hidden by an initializer_list
constructor.
However, the reason this should be generally “rare” is because default
and copy construction are already special and work fine with { }, and
good class design now mostly avoids the resort-to-( ) case for
user-defined constructors because of this final design guideline:
Guideline: When you design a class, avoid providing a constructor that
ambiguously overloads with an initializer_list constructor, so that
users won’t need to use ( ) to reach such a hidden constructor.
Also see the Core Guidelines on that subject: ES.23: Prefer the {}-initializer syntax.
It only safer as long as you don't build with -Wno-narrowing like say Google does in Chromium. If you do, then it is LESS safe. Without that flag the only unsafe cases will be fixed by C++20 though.
Note:
A) Curly brackets are safer because they don't allow narrowing.
B) Curly brackers are less safe because they can bypass private or deleted constructors, and call explicit marked constructors implicitly.
Those two combined means they are safer if what is inside is primitive constants, but less safe if they are objects (though fixed in C++20)
With C++11 came a new way to initialize and declare variables.
Original
int c_derived = 0;
C++11
int modern{0};
What are the pros and cons of each method, if there are any? Why implement a new method? Does the compiler do anything different?
You're mistaken -- the int modern(0) form (with round brackets) was available in older versions of C++, and continues to be available in C++11.
In C++11, the new form uses curly brackets to provide uniform initialisation, so you say
int modern{0};
The main advantage of this new form is that it can be consistently used everywhere. It makes it clear that you're initialising a new object, rather than calling a function or, worse, declaring one.
It also provides syntactical consistency with C-style ("aggregate") struct initialisation, of the form
struct A
{
int a; int b;
};
A a = { 1, 2 };
There are also more strict rules with regard to narrowing conversions of numeric types when the curly-bracket form is used.
Using braces was just an attempt to introduce universal initialization in C++11.
Now you can use braces to initialize arrays,variables,strings,vectors.
Which of the following declaration is the standard and preferred?
int x = 7;
or
int x(7);
int x(7);
is not the valid way of declaring & initializing a variable in C;
I suggest you to get a good book for learning C and use a good compiler.
in c kind of langueges you normally use
int x = 7;
You've tagged this question as both C and C++, but the answers aren't really the same for the two.
In C, int x(7); simply doesn't work. It won't even compile. Since this form doesn't work at all in C, the preferred form is int x = 7;.
In C++, int x(7); works -- but you have to be careful, as this form can lead to the "most vexing parse"; if whatever was in the parentheses could be interpreted as a type instead of a value, this would be parsed as declaring a function named x that returned an int instead of defining an int with the value specified in the parentheses. Likewise, if you leave the parens empty: int x(); you end up with a function declaration.
C++ does have another form: int x{7};. Some call this "universal initialization". It does remove any ambiguity -- anything like T id { x }; where T is a type must be a definition of a id with x as an initializer. Some people dislike this, however, because it introduces somewhat different semantics -- for example, "narrowing" conversions are prohibited in this case, so you can't blindly change existing code to use the new form. For example:
int x(12.34); // no problem
int y{ 12.34 }; // won't compile -- double -> int is a narrowing conversion
This isn't particularly likely to happen with a literal as I've shown above, but something like:
void f(double x) {
int y(x);
// ...
...is rather more likely -- and still isn't allowed.
Unfortunately, going "back" to the C-style initialization doesn't cure all the possible problems either. At least in theory, it does copy initialization instead of direct initialization, so the type you're initializing must have a copy constructor available to do this initialization. For example:
class T {
T(T const &) = delete;
public:
T(int) {}
};
int main() {
T t = 1;
}
This isn't officially allowed to work, because what it's supposed to do is use T(int) to create a temporary T object, then use T(T const &) to copy-construct t from that temporary. Since we've deleted the copy constructor, it can't (officially) be used. This can be particularly confusing, because nearly all compilers will normally do the job without using the copy constructor at all, so the code will normally compile and work just fine--but the minute you turn on the mode where the compiler tries to follow the standard as closely as possible, the code won't compile at all.
Some people find the changes in "uniform initialization" so off-putting that they recommend against using it at all. Personally, I prefer to use it and simply ensure that I'm not doing any narrowing conversions (or use an explicit cast if a narrowing conversion just can't be avoided).
In general
int x = 7;
is the standard way, and the ONLY way in C.
However, in C++, you can initialize an int using x(7) in cases such as constructor initializer lists, where you have to invoke a 'constructor' for each variable you are initializing that way. For primitives, you do this with the x(7) syntax.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a difference in C++ between copy initialization and direct initialization?
I just started to learn C++.
To initialize a variable with a value, I came across
int a = 0;
and
int a(0);
This confuses me a lot. May I know which is the best way?
int a = 0; and int a(0); make no difference in the machine generated code. They are the same.
Following is the assembly code generated in Visual Studio
int a = 10; // mov dword ptr [a],0Ah
int b(10); // mov dword ptr [b],0Ah
They're both the same, so there really is no one "best way".
I personally use
int a = 0;
because I find it more clear and it's more widely used in practice.
This applies to your code, where the type is int. For class-types, the first is copy-initialization, whereas the other is direct-initialization, so in that case it would make a difference.
There's no "best" way. For scalar types (like int in your example) both forms have exactly the same effect.
The int a(0) syntax for non-class types was introduced to support uniform direct-initialization syntax for class and non-class types, which is very useful in type-independent (template) code.
In non-template code the int a(0) is not needed. It is completely up to you whether you want to use the int a(0) syntax, or prefer to stick to more traditional int a = 0 syntax. Both do the same thing. The latter is more readable, in my opinion.
From a practical point of view: I would only use int a = 0;.
The int a(0) may be allowed but never used in practice in itself.
I think it should not bother you on your level, but let us go further.
Let's say that a is a class, not an int.
class Demo{
public:
Demo(){};
Demo(int){};
};
Demo a;
Demo b(a);
Demo c = a; // clearly expressing copy-init
In this example both b(a) and c=a do the same, and I would discourage you using the fist solution. My reason is, that is looks similar to c(2) which is a construction from arguments.
There are only two valid uses of this bracket-style initialization:
initialization lists (Demo(int i):data(i){} if Demo has an int data member data),
new's: Demo *p=new Demo(a); // copy constructing a pointer
It’s that simple. (Well, almost — there are a few things you can’t name your variables, which we’ll talk about in the next section)
You can also assign values to your variables upon declaration. When we assign values to a variable using the assignment operator (equals sign), it’s called an explicit assignment:
int a= 5; // explicit assignment
You can also assign values to variables using an implicit assignment:
int a(5); // implicit assignment
Even though implicit assignments look a lot like function calls, the compiler keeps track of which names are variables and which are functions so that they can be resolved properly.
In textbooks and literature, one is direct initialization and the other is copy initialization. But, in terms of machine code, there is no difference.
The difference is that () initialization is when you explicitly want it to take one parameter only, e.g:
You can:
int a = 44 + 2;
but you can't:
int a(44) + 2;