Imagine you have a class similar to the one that shows the problem you asked in the question
class Foo{}; class Bar { public: Foo* mFoo; Bar() : mFoo( new Foo() ) {} ~Bar() { delete mFoo;} };
And code like this
Bar x ; Bar y = x;
The above code will cause a core dump, since both y and x will point to the same Foo , and the destructor will try to delete the same Foo twice.
ALTERNATIVE 1
Declare but not provide a definition so that Bar never creates a constructor or assigns it. Will guarantees that Bar y = x will have a communication error, since you created a class that will not be copied.
class Bar { public: Foo* mFoo; Bar() : mFoo( new Foo() ) {} ~Bar() { delete mFoo;} Bar(const Bar &); Bar& operator= (const Bar &); };
ALTERNATIVE 2
Provide a copy constructor and assignment operator that do the right thing. Instead of having the compiler provide a default copy and assignment implementation that make a shallow copy, you duplicate Foo so that both x and y have their own Foo
class Bar { public: Foo* mFoo; Bar() : mFoo( new Foo() ) {} ~Bar() { delete mFoo;} Bar(const Bar & src) { mFoo = new Foo( *(src.mFoo) ); } Bar& operator= (const Bar & src) { mFoo = new Foo( *(src.mFoo) ); return *this; } };
ALTERNATIVE 3 (BEST)
Use C ++ 11 shared_ptr or increase and omit copy and assignment, since the default compiler provides the correct operation, since shared_ptr only counts and removes Foo once, although both x and y have the same Foo . Also note that ~Bar does not require explicit cleanup, since mFoo will be automatically deleted in the std::shared_ptr<Foo> destructor when refcount Foo becomes zero.
class Bar { public: std::shared_ptr<Foo> mFoo; Bar() :mFoo( new Foo() ) {} ~Bar() { } };
source share