Weird c++ copy constructor without default constructor [duplicate]
Asked Answered
K

1

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;
Knavish answered 13/5, 2015 at 10:7 Comment(3)
"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?Jd
Valid point. Do you suggest that Pt pt = Pt(); could call copy constructor in some case? If so - could you give an example?Knavish
@Vorren - about this Pt pt = Pt(), I updated my answer.Mckenna
M
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++

Mckenna answered 13/5, 2015 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.