2012-12-24 70 views
2

我需要使用RAII成語,我在做正確的事:?如何使用std :: auto_ptr作爲函數的參數?

std::auto_ptr<std::vector<string>> MyFunction1() 
{ 
    std::auto_ptr<std::vector<string>> arrayOfStrings; 

    MyFunction2(arrayOfStrings); // work with arrayOfStrings 

    return arrayOfStrings; 
} 

void MyFunction2(std::auto_ptr<std::vector<string>> array) 
{ 
    auto_ptr<string> str; 
    *str = "foo string"; 
    array.push_back(str) 
} 

或許shoudl我自己釋放內存,而不是使用智能指針?如果是這樣,該怎麼做?提前致謝。

+2

只需注意:'std :: auto_ptr'現在已被棄用。它試圖在移動語義存在之前實現移動語義。看看'std :: unique_ptr',它正確地做到了。 –

+0

看看'std :: shared_ptr',那應該解決這個問題。 – Zaffy

回答

4

只要不使用指針,即使不聰明的人在這種情況下:

std::vector<string> MyFunction1() 
{ 
    std::vector<string> arrayOfStrings; 
    MyFunction2(arrayOfStrings); // work with arrayOfStrings 
    return arrayOfStrings; 
} 

void MyFunction2(std::vector<string> &array) 
{ 
    array.push_back("foo string"); 
} 

編譯器必將優化的返回值拷貝走,將被稱爲Return Value Optimization優化,所以你不應該擔心那。在這種情況下,使用指針避免複製可能最終導致效率低下並且繁瑣,與使用堆棧中分配的對象並依賴於此優化相比。

否則,考慮使用std::unique_ptr作爲@templatetypedef提及。儘可能避免使用指針。

4

如果您的函數按值取值爲std::auto_ptr,那麼您傳入該函數的任何std::auto_ptr都將放棄對該資源的控制權,並將其交給它調用的函數。因此,函數返回時,原始std::auto_ptr將不再指向它最初指向的資源。因此,你可以考慮以價值觀來接受std::auto_ptr,他說:「我將把你的資源從你身上拿走,並且用它做點什麼。」

要解決這個問題,請考慮讓你的函數參考std::auto_ptr,它不會竊取參考。

但是,說,你應該停止使用std::auto_ptr並開始使用std::unique_ptr來代替。 std::unique_ptr是一個更安全,更健全的std::auto_ptr替代品。您無法通過價值傳遞std::unique_ptr而沒有明確使用std::move放棄對資源的控制,並且沒有任何「難以捉摸」的風格驚喜。

希望這會有所幫助!

+0

+1,但錯過了一個重要方面:OP從未初始化指針。 –

相關問題