【问题标题】:Can I explicitly call an object's destructor in an instance of another class?我可以在另一个类的实例中显式调用对象的析构函数吗?
【发布时间】:2012-10-25 21:09:58
【问题描述】:

我正在使用两个队列来实现一个堆栈作为练习。我在堆栈类的每个实例中都有两个队列对象。我希望堆栈的析构函数调用队列的析构函数。从网上看,析构函数的显式使用似乎并不常见,因为它们往往会被自动调用。我的代码:

template<class T>
class Stack {
// LIFO objects
   public:
      Stack(int MaxStackSize = 10);
      ~Stack();

      bool IsEmpty() const {return addS.IsEmpty();}
      bool IsFull() const {return addS.getSize()==maxSize;}

      Stack<T>& Add(const T& x);
      Stack<T>& Delete(T& x);
      void Print() const;
   private:
      LinkedQueue<T> addS;
      LinkedQueue<T> delS;
      int maxSize;
};

template<class T>
Stack<T>::Stack(int MaxStackSize)
{
   maxSize = MaxStackSize;
}

template<class T>
Stack<T>::~Stack()
{
   ~addS();
   ~delS();
}

template<class T>
class LinkedQueue {
// FIFO objects
    public:
        LinkedQueue() {front = rear = 0;} // constructor
        ~LinkedQueue(); // destructor
        bool IsEmpty() const
           {return ((front) ? false : true);}
        bool IsFull() const;
        T First() const; // return first element
        T Last() const; // return last element
        LinkedQueue<T>& Add(const T& x);
        LinkedQueue<T>& Delete(T& x);
      void Print() const;  // print the queue in order
      int getSize() const;

   private:
      Node<T> *front;  // pointer to first node
      Node<T> *rear;   // pointer to last node
};

template<class T>
LinkedQueue<T>::~LinkedQueue()
{// Queue destructor.  Delete all nodes.
   Node<T> *next;
   while (front) {
      next = front->link; 
      delete front; 
      front = next;
      }
}

运行上面的代码给我以下错误:

stack.h:在析构函数“Stack::~Stack() [with T = int]”中: stackrunner.cc:9:从这里实例化 stack.h:37:错误:不匹配 用于调用'(LinkedQueue) ()'

我是否错误地调用了析构函数?我不应该调用析构函数吗?调用类析构函数时会自动调用对象析构函数吗?

【问题讨论】:

  • 会为你调用析构函数。

标签: c++ class object destructor


【解决方案1】:

会自动为您调用析构函数。

在已经销毁的对象上调用析构函数是未定义的行为。它可能会崩溃,或导致任意结果,或造成真正的损害。

通常,从不显式调用析构函数(除非您一直使用placement new 在现有存储中构造对象)。

【讨论】:

  • 类对象的析构函数是否在类析构函数中调用?
猜你喜欢
  • 2014-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多