Anti-nuisance lawsuit warning: The purpose of these notes is to remind me, Zoegond, of stuff or to help me work stuff out. They may contain mistakes.

Quick

  • ($a, $b....) = unpack("A2A7...", $packed)
  • push( array, list )

Saturday, December 22, 2012

Copy constructor

If you don't define a copy constructor - a Thing(const Thing &t)() constructor - the compiler will generate a default one which just copies all the members bit-for-bit.

This is bad because the copy constructor is used, not just for stuff like

Thing t1 = Thing(t0);

but also for initialising arguments to functions, so if you have

void f(Thing a) { ... }

Thing t;
f(t);


the copy constructor will be used when a is created. And if it's the default one, all a's members will be literally and exactly the same as t's, even if their pointers. Particularly bad news if your destructor deletes those pointers - because at the end of f(), ~Thing will be called on a, and the referents of a's pointers are the same as the referents of t's pointers, so when f() has returned, t will have lost those referents.

So, in short, if you want to pass your class to functions, make a copy constructor for it.

Followers

Blog Archive