I can't seem to find anything online about the differences between these two. Almost every teaching source online (learncpp.com, cplusplus.com etc) seem to all use Obj x(n); to initialize Obj x, but when I use Obj x = Obj(n), my compiler doesn't complain and I see no difference. Is there actually a difference, or is it just a style choice?
Asked
Active
Viewed 181 times
0
R Sahu
- 204,454
- 14
- 159
- 270
Teofrostus
- 1,506
- 4
- 18
- 29
-
In the original question the answers were pre c++11. I have added an answer which may be more relevant according to the current standard. – bashrc May 18 '15 at 04:34
2 Answers
3
Using
Obj x(n);
is called Direct Initialization. It calls the constructor that can accept n as an argument to initialize x.
Using
Obj x = Obj(n);
is called Copy Initialization. In theory, this constructs a temporary Obj using n and calls the copy constructor to initialize x. Some compilers are able to optimize away the temporary.
R Sahu
- 204,454
- 14
- 159
- 270
-
Thanks for this answer. I couldn't figure out what these two cases were called. Now I can read the links. – Teofrostus May 18 '15 at 04:14
0
Obj x(n); declared x as an Obj, and then constructs it.
Obj x = Obj(n) declares x as an Obj, then initializes it to the result of the construction of a temporary.
The first case is faster and generates less machine code.
user703016
- 37,307
- 8
- 87
- 112
Mike Crawford
- 2,232
- 2
- 18
- 28
-
1
-
Re: "The first case is faster and generates less machine code": Is this necessarily the case? I thought that compilers were allowed to perform [copy elision](http://en.wikipedia.org/wiki/Copy_elision) in cases like this? – ruakh May 18 '15 at 04:10
-
So, if the compiler does perform the optimizations you're talking about, then is it just a style choice? Is there any reason I shouldn't use whichever one I like the looks of more? – Teofrostus May 18 '15 at 04:11
-
I was going to mention the possibility of optimizing away the temporary, however I'm concerned that it's not really safe to do so. Admittedly a constructor that was written in such a way that that optimization would be a bad idea, but would be legal C++. – Mike Crawford May 18 '15 at 18:52