C++ 中的 RA​​II 和智慧指標


C++ 中的 RA​​II

RA​​II(資源獲取即初始化)是 C++ 技術,它控制資源的生命週期。它是一個類變體,與物件生命週期繫結。

它將多個資源封裝到類中,其中資源分配由物件建立時的建構函式完成,而資源釋放由物件銷燬時的解構函式完成。

在物件存活期間,保證持有資源。

示例

void file_write {
   Static mutex m; //mutex to protect file access
   lock_guard<mutex> lock(m); //lock mutex before accessing file
   ofstream file("a.txt");
   if (!file.is_open()) //if file is not open
   throw runtime_error("unable to open file");
   // write text to file
   file << text << stdendl;
}

C++ 中的智慧指標 & 減號;

智慧指標是一種抽象資料型別,我們可以使用它以一種方式製作一個普通指標,使其可以像檔案處理、網路套接字等記憶體管理一樣使用,此外它還可以做很多事情,如自動銷燬、引用計數等。

C++ 中的智慧指標可以實現為模板類,它過載了 * 和 -> 運算子。auto_ptr、shared_ptr、unique_ptr 和 weak_ptr 是 C++ 庫可以實現的智慧指標形式。

示例

 即時演示

#include <iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class Smartpointer {
   T *p; // Actual pointer
   public:
      // Constructor
      Smartpointer(T *ptr = NULL) {
         p = ptr;
      }
   // Destructor
   ~Smartpointer() {
      delete(p);
   }
   // Overloading de-referencing operator
   T & operator * () {
      return *p;
   }
   // Over loading arrow operator so that members of T can be accessed
   // like a pointer
   T * operator -> () {
      return p;
   }
};
int main() {
   Smartpointer<int> p(new int());
   *p = 26;
   cout << "Value is: "<<*p;
   return 0;
}

輸出

Value is: 26

更新時間:2019 年 7 月 30 日

1000 多次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.