menu

hjk41的日志

Avatar

More Effecitve C++ 27: Requiring or prohibiting heap-base objects

1. When created using new, objects are placed on the heap, otherwise on the stack. However, static objects are placed neither on the heap, nor on the stack; they are placed somewhere else.

2. By declaring destructor private, you can prevent objects from being created on the stack. And when deleting the object, you can declare a public member function that deletes this:


class UPNumber {
public:
  UPNumber();
  // pseudo-destructor (a const member function, because
  // even const objects may be destroyed)
  void destroy() const { delete this; }
  ...
private:
  ~UPNumber();
};
UPNumber n;                   // error! (legal here, but
                                     // illegal when n's dtor is
                                     // later implicitly invoked)

UPNumber *p = new UPNumber;          // fine

...

delete p;                            // error! attempt to call
                                     // private destructor

p->destroy();                        // fine


However, private destrutor will prohibit inheritance, so we should declare it protected.

评论已关闭