FAQ 12.15 How can class Fred guarantee that Fred objects are created only with new and not on the stack?

FAQ 12.15 How can class Fred guarantee that Fred objects are created only with new and not on the stack?

graphics/new_icon.gif

The class can make all of its constructors private: or protected: and can provide static create() member functions. The copy constructor should also be made private: or protected:, even if it doesn't need to be defined otherwise (see FAQ 30.06). The static (or friend) create() functions then create the object using new and return a pointer to the allocated object. Here's an example.

 #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:.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net