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;
Constructions like type object = something
call copy constructors, not assignment operators
Having this in mind, here's what happens:
Pt pt =
-> at this point, Pt
object is created, named pt
(nothing is initialized at this point)= pt;
-> at this point, pt
's copy constructor is called with argument - itself (pt
)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++
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With