Suppose I have a class that requires copy constructor to be called to make a correct copy of:
struct CWeird
{
CWeird() { number = 47; target = &number; }
CWeird(const CWeird &other) : number(other.number), target(&number) { }
const CWeird& operator=(const CWeird &w) { number = w.number; return *this; }
void output()
{
printf("%d %d\n", *target, number);
}
int *target, number;
};
Now the trouble is that CArray doesn't call copy constructors on its elements when reallocating memory (only memcpy from the old memory to the new), e.g. this code
CArray<CWeird> a;
a.SetSize(1);
a[0].output();
a.SetSize(2);
a[0].output();
results in
47 47
-572662307 47
I don't get this. Why is it that std::vector can copy the same objects properly and CArray can't? What's the lesson here? Should I use only classes that don't require explicit copy constructors? Or is it a bad idea to use CArray for anything serious?