the problem of copy ctor

May 31, 2009 at 1:38am
class A {
int *p;

public:
A(int N){ p = new int[N];}

~A() {delete [] p; p = NULL;}
};

int main() {
A a(5);
A b = a;
}

It fails after the last statement, what's the problem
Last edited on May 31, 2009 at 1:52am
May 31, 2009 at 1:56am
A a(5);
This creates an A, which allocates 5 ints.
A b = a;
This calls the compiler-generated copy constructor which looks something like this:
1
2
3
A::A(const A &src){
    this->p=src.p;
}

When main() returns, both a and b are destructed. Since both of their 'p's point to the same array, after the first A is destructed, the other's p is no longer valid, so when it's destructed it will produce a segmentation fault.

Always write your own copy constructors if you're doing dynamic allocation.
May 31, 2009 at 2:18am
I just add the copy ctor to the code, it still fails, maybe it's because the memory is not cleared properly, but I don't know how to do that. Besides, can you tell what's tool do you use to add the code as above, thanks.
Last edited on May 31, 2009 at 2:22am
May 31, 2009 at 2:26am
Are you allocating an array for the new object or did you just copy the example I wrote above?
Topic archived. No new replies allowed.