Stanley Stuart
Stanley Stuart

Reputation: 1145

C++ Should I destroy old objects in an object when setting new objects?

Consider the following class declaration:

#include "classB.h"
class A {
private:
    B *prop;

public:
    A() { /* does stuff to set up B as a pointer to a new B */
    setB(const B& bar) { /* store a copy of B */
        // how do I manage the old *prop?
        *prop = new B(bar);
    }
};

In setB() how should manage the memory allocation? Should I delete the old *prop? If so, do I dereference and then delete?

Upvotes: 1

Views: 521

Answers (3)

Stuart Golodetz
Stuart Golodetz

Reputation: 20616

In order to maintain the state of the object as it was before the operation in the case that the allocation throws, you might be better off implementing it something like this:

void setB(const B& bar)
{
    // Do this first, since it could throw.
    B *newProp = new B(bar);

    // Now delete the old one and replace it with the new one.
    delete prop;
    prop = newProp;
}

See here (specifically the bit about the strong exception guarantee):

http://en.wikipedia.org/wiki/Exception_guarantees

Upvotes: 2

Bo Persson
Bo Persson

Reputation: 92231

If the constructor always allocates a new B, you can just reuse that space for your copies of other B objects.

A() { /* does stuff to set up prop as a pointer to a new B */
}

setB(const B& bar) { /* store a copy of B */
    *prop = bar;
}

And don't forget to delete prop in the destructor.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258568

First, you have to set prop to NULL in the constructor, otherwise you'd get undefined behavior if you attempt to delete it.

Second, you don't dereference, you just assign the pointer.

Third, you should delete the memory in the destructor so you don't get a leak.

Last, if you implement the destructor, you should also have a copy constructor and an assignment operator.

class A {
private:
    B *prop;

public:
    //set prop to NULL so you don't run into undefined behavior
    //otherwise, it's a dangling pointer
    A() { prop = NULL; }

    //when you set a new B, delete the old one
    setB(const B& bar) { 
        delete prop;
        prop = new B(bar);
    }

    //delete prop in destructor
    ~A() { delete prop; }

    //because you now have a destructor
    //implement the following to obey the rule of three
    A& operator = (const A& other);  //assignment operator
    A(const A& other);               //copy constructor
};

Upvotes: 5

Related Questions