0

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?

R Sahu
  • 200,579
  • 13
  • 144
  • 260
Teofrostus
  • 1,386
  • 4
  • 16
  • 28
  • 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 Answers2

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
  • 200,579
  • 13
  • 144
  • 260
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
  • 36,281
  • 7
  • 84
  • 109
Mike Crawford
  • 2,110
  • 1
  • 16
  • 25
  • 1
    Not true, any decent compiler will optimize away the temporary. – user703016 May 18 '15 at 04:10
  • 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