使用 C++ 中的共享指標進行虛擬析構


在本教程中,我們將討論一個程式,瞭解如何使用 C++ 中的共享指標進行虛擬析構。

為了刪除類例項,我們定義虛基類的解構函式。因此,它將按建立的相反順序刪除繼承的不同物件例項。

示例

 即時演示

#include <iostream>
#include <memory>
using namespace std;
class Base {
   public:
   Base(){
      cout << "Constructing Base" << endl;
   }
   ~Base(){
      cout << "Destructing Base" << endl;
   }
};
class Derived : public Base {
   public:
   Derived(){
      cout << "Constructing Derived" << endl;
   }
   ~Derived(){
      cout << "Destructing Derived" << endl;
   }
};
int main(){
   std::shared_ptr<Base> sp{ new Derived };
   return 0;
}

輸出

Constructing Base
Constructing Derived
Destructing Derived
Destructing Base

更新於:12-Mar-2020

145 次觀看

開啟你的職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.