1. 要求对象产生于堆中

    由于non-heap 对象会在定义时自动构造,并在寿命结束时自动析构,因此要阻止客户产生non-heap对象,只需要将构造或析构函数声明为private.又由于构造函数可能有多个,儿媳够函数只有一个,因此更好的选择是将析构函数声明为private,然后开放一接口调用它,像这样:

class UPNumber {
public:
    UPNumber();
    UPNumber(int initValue);
    UPNumber(double initValue);
    UPNumber(const UPNumber& rhs);
    // pseudo destructor,它是const menber function,因为const对象也需要被销毁
    void destroy() const { delete this; }
    ...
private:
    ~UPNumber();
};
View Code

相关文章:

  • 2021-07-20
  • 2021-08-26
  • 2021-10-26
  • 2021-11-23
  • 2021-07-03
  • 2021-08-02
  • 2022-01-16
  • 2022-12-23
猜你喜欢
  • 2021-11-22
  • 2021-09-09
  • 2022-12-23
  • 2022-03-09
  • 2021-06-23
  • 2022-12-23
相关资源
相似解决方案