CArray doesn't call copy constructors on memory reallocations, now what?

Posted by MMx on Stack Overflow See other posts from Stack Overflow or by MMx
Published on 2010-05-28T10:58:14Z Indexed on 2010/05/28 11:12 UTC
Read the original article Hit count: 137

Filed under:
|
|
|

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) { }

    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?

© Stack Overflow or respective owner

Related posts about c++

Related posts about mfc