共用方式為


CAutoPtr Class

這個類別表示智慧型指標物件。

重要

這個類別和其成員不能用於 Windows 執行階段執行的應用程式。

template< 
typename T 
> 
class CAutoPtr

參數

  • T
    指標型別。

Members

公用建構函式

名稱

描述

CAutoPtr::CAutoPtr

建構函式。

CAutoPtr::~CAutoPtr

解構函式。

公用方法

名稱

描述

CAutoPtr::Attach

呼叫這個方法會接受一個現有指標的擁有權。

CAutoPtr::Detach

呼叫這個方法會釋放指標的擁有權。

CAutoPtr::Free

呼叫這個方法會刪除上的物件。 CAutoPtr

公用運算子

名稱

描述

CAutoPtr::operator T*

轉型運算子。

CAutoPtr::operator =

指派運算子。

CAutoPtr::operator ->

成員指標運算子。

公用資料成員

名稱

描述

CAutoPtr::m_p

指標資料成員變數。

備註

這個類別會建立和管理的智慧型指標提供方法,可協助防止記憶體遺漏 (Memory Leak) 會自動釋放資源,並在超出範圍時。

此外, CAutoPtr 的複製建構函式和指派運算子傳輸,複製來源指標的指標和設定來源指標的指標的擁有權 null。 有兩 CAutoPtr 物件儲存相同指標的每個也是不可能的,因此,這會減少兩次刪除相同指標的可能性。

CAutoPtr 也簡化了指標集合的建立。 取代衍生集合類別和覆寫解構函式,是較簡單的執行 CAutoPtr 集合物件。 當集合中刪除, CAutoPtr 物件會超出範圍並自動刪除。

CHeapPtr 和 Variant 與 CAutoPtr類似的方式運作,不過,這些配置和釋放記憶體使用不同的堆積函式而不是 C++ new刪除 運算子。 CAutoVectorPtr 類似 CAutoPtr,是唯一差別在於它會使用 vector new[]vector delete[] 配置和釋放記憶體。

如果需要,請參閱 CAutoPtrArrayCAutoPtrList 智慧型指標陣列或清單。

需求

Header: atlbase.h

範例

// A simple class for demonstration purposes 

class MyClass 
{
   int iA;
   int iB;
public:
   MyClass(int a, int b);
   void Test();
};

MyClass::MyClass(int a, int b)
{
   iA = a;
   iB = b;
}

void MyClass::Test()
{
   ATLASSERT(iA == iB);
}

// A simple function 

void MyFunction(MyClass* c)
{
   c->Test();
}

int UseMyClass()
{
   // Create an object of MyClass.
   MyClass *pMyC = new MyClass(1, 1);

   // Create a CAutoPtr object and have it take 
   // over the pMyC pointer by calling Attach.
   CAutoPtr<MyClass> apMyC;
   apMyC.Attach(pMyC);

   // The overloaded -> operator allows the  
   // CAutoPtr object to be used in place of the pointer.
   apMyC->Test();

   // Assign a second CAutoPtr, using the = operator.
   CAutoPtr<MyClass> apMyC2;
   apMyC2 = apMyC;

   // The casting operator allows the 
   // object to be used in place of the pointer.
   MyFunction(pMyC);
   MyFunction(apMyC2);

   // Detach breaks the association, so after this 
   // call, pMyC is controlled only by apMyC.
   apMyC2.Detach();

   // CAutoPtr destroys any object it controls when it 
   // goes out of scope, so apMyC destroys the object  
   // pointed to by pMyC here. 
   return 0;
}

請參閱

參考

CHeapPtr Class

CAutoVectorPtr Class

其他資源

ATL Class Overview