Consider the following code:
class A
{
B* b; // an A object owns a B object
A() : b(NULL) { } // we don\'t know what b will be when constructing A
I'd go with boost::scoped_ptr here:
class A: boost::noncopyable
{
typedef boost::scoped_ptr b_ptr;
b_ptr pb_;
public:
A() : pb_() {}
void calledVeryOften( /*…*/ )
{
pb_.reset( new B( params )); // old instance deallocated
// safely use *pb_ as reference to instance of B
}
};
No need for hand-crafted destructor, A
is non-copyable, as it should be in your original code, not to leak memory on copy/assignment.
I'd suggest to re-think the design though if you need to re-allocate some inner state object very often. Look into Flyweight and State patterns.