9

Me and a colleague of mine had a debate about wether

Pt pt;

and

Pt pt = Pt(); 

are equivalent. I suspected that in the second case copy assignment could be called, but as it turns out it isn't the case.

As we ran our little experiment I decided to test a weird bit, that my colleague thought wouldn't even compile:

//here the compiler calls a copy constructor and doesn't call the default constructor prior to that
// O_o
Pt pt = pt;

Here is a working sample: http://ideone.com/XmJSz7

So, the question is - what goes on in:

Pt pt = pt;
gsamaras
  • 71,951
  • 46
  • 188
  • 305
pdeschain
  • 1,411
  • 12
  • 21
  • "*I suspected that in the second case copy assignment could be called, but as it turns out it isn't the case.*" I suspect you're concluding from the fact that something didn't happen that it couldn't happen. This is invalid reasoning. If I walk across the street without looking both ways and don't get hit by a car, does that mean someone who said I could have gotten hit by a car was incorrect? – David Schwartz May 13 '15 at 10:45
  • Valid point. Do you suggest that Pt pt = Pt(); could call copy constructor in some case? If so - could you give an example? – pdeschain May 13 '15 at 10:50
  • @Vorren - about this `Pt pt = Pt()`, I updated my answer. – Kiril Kirov May 13 '15 at 10:56

1 Answers1

6

Constructions like type object = something call copy constructors, not assignment operators

Having this in mind, here's what happens:

  1. Pt pt = -> at this point, Pt object is created, named pt (nothing is initialized at this point)
  2. = pt; -> at this point, pt's copy constructor is called with argument - itself (pt)
  3. as pt is created BUT not initialized (in 1.), this is (kinda) valid - pt's copy constructor (in 2.) will be "properly" executed, taking as right-hand-side argument the already existing and uninitialized object pt (from 1. again)

Shortly - this is bad.

It's worth noting, that if the pt object is global or static, it will be default-initialized at step 1. - after reaching the =.

EDIT: regarding the initial "puzzle" Pt pt = Pt();, you can see this question: Is there a difference in C++ between copy initialization and direct initialization? and its accepted answer. And this one seems interesting, too: How variable is initialized by default constructor in c++

Community
  • 1
  • 1
Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187