2010-09-08 33 views
2

以前,我有以下代碼。是否有任何需要分配空指針std :: auto_ptr

double* a[100]; 
for (int i = 0; i < 100; i++) { 
    // Initialize. 
    a[i] = 0; 
} 

a 0初始化數組的目的是,當我反覆刪除a元素,一切都將正常工作,甚至還沒有仍然分配給的a元素記憶。

for (int i = 0; i < 100; i++) { 
    // Fine. 
    delete a[i]; 
} 

現在,我想利用auto_ptr,避免手動調用刪除。

std::auto_ptr<double> a[100]; 
for (int i = 0; i < 100; i++) { 
    // Initialize. Is there any need for me to do so still? 
    a[i] = std::auto_ptr<double>(0); 
} 

我想知道,是否有任何需要我來初始化auto_ptr持有空指針?我的感覺不是。我只想確認一下,這樣就沒有任何障礙。

+2

也許你可以解釋爲什麼你想要一個指針數組在第一位加倍。將它改爲'auto_ptr '的數組聽起來像是它缺少真正的問題。 – 2010-09-08 02:26:18

回答

6

的C++ 03指定的auto_ptr的構造如下:

explicit auto_ptr(X* p =0) throw();    // Note the default argument 

Postconditions: *this holds the pointer p. 

這意味着下面的是完全良好的。沒有必要初始化

auto_ptr<int> a = auto_ptr<int>(); 
2

您可以零使用初始化數組的所有成員:

double* a[100] = {0}; // is equivalent 

使用for_each來刪除一個選擇:

struct delete_object 
{ 
    template <typename T> 
    void operator()(T *ptr){ delete ptr;} 
}; 

//later in the code... 
std::for_each(&a[ 0 ], &a[ 0 ] + sizeof a/sizeof a[ 0 ], delete_object()); 

現在對於你的問題:

是否有是否需要我初始化auto_ptr來保存一個空指針?

沒有必要初始化auto_ptr的數組。如果你離開它,成員將被默認初始化。

但是,請注意auto_ptr可能不適用於其移動語義(所有權副本),如果您需要傳遞指向其他函數的指針。此外,在即將推出的標準auto_ptr可能會被棄用。嘗試使用類似std::tr1::unique_ptrstd::tr1::shared_ptr(後者是引用計數的智能指針)。

6

std::auto_ptr的默認構造函數的NULL賦值爲你 - 或者,作爲標準(ISO/IEC 14882:1998)所說的那樣,構造函數聲明爲:

明確的auto_ptr(X * P = 0)throw();

X是模板參數類,即,這是用於std::auto_ptr<X>)。

相關問題