Help with dynamic memory

Hi, I have a little problem with this piece of code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class PInt {
    private:
        int* n;
        int id;
    public:
        PInt( int o, int q ):id( q ) {
            n = new int(o);
        }
        ~PInt(){ delete n; n = 0;}
        int Id() { return id; }
        void SetId( int i ) { id = i; }
        int N() { return *n; }
        void SetN( int n_ ) { *n = n_; }
        void What() { std::cout << "ID: " << Id() << " + *N: " << N() << "\n"; }
};

int main() {
    int* p1=new int(1);
    std::vector<PInt> v;
    PInt x1( *p1, 0 );

    x1.What();
    v.push_back( x1 );
    printf("----------------------\n");
    x1.SetN( 7000 );
    std::cout << "X1-> "; x1.What();
    std::cout <<"*p1: " << *p1 << std::endl;
    std::cout << "v[0]-> "; v[0].What();
}


It crashes on execution. Any ideas? Thanks in advance.
Since you don't provide a copy constructor for PInt, the compiler provides one for you. The compiler-provided constructor will just copy the values of your variables n and id. Since n is a pointer, you end up with two PInt's that point to the exact same memory address using the two variables n.

When the main function finishes the destructors of the two PInt's are called: The first one succeeds without issues, but the second one calls delete on memory that has already been deleted.

Solution: Provide a suitable copy constructor.
So, the copy constructor is needed when I do v.push_back( x1), is it?
Correct. Pushing an item into the vector is actually just copying it. This is where the pointer gets duplicated.
I wrote the copy constructor and it worked. Thanks!!
Topic archived. No new replies allowed.