FAQ 12.15 How can class Fred guarantee that Fred objects are created only with new and not on the stack?
#include <new> #include <memory> using namespace std; class Fred; // Forward declaration typedef auto_ptr<Fred> FredPtr; class Fred { public: static FredPtr create() throw(bad_alloc); static FredPtr create(int i) throw(bad_alloc); static FredPtr create(const Fred& x) throw(bad_alloc); virtual void goBowling(); private: Fred(int i=10) throw(); Fred(const Fred& x) throw(); int i_; }; FredPtr Fred::create() throw(bad_alloc) { return new Fred(); } FredPtr Fred::create(int i) throw(bad_alloc) { return new Fred(i); } FredPtr Fred::create(const Fred& x) throw(bad_alloc) { return new Fred(x); } Fred::Fred(int i) throw() : i_(i) { } Fred::Fred(const Fred& x) throw() : i_(x.i_) { } void sample() { FredPtr p(Fred::create(5)); p->goBowling(); } Note that derived classes can't be instantiated since all of the constructors are private:. Derived classes could be instantiated only if some of the constructors were protected:. |