2011-02-10 38 views
0

我有做這樣的功能:通行證指針auto_ptr的用C++

static MyClass* MyFunction(myparams) 
{ 
    return new MyClass(myparams) 
} 

和我將能夠調用內另一個具有以下簽名此功能:

void MyFunction2(std::auto_ptr<MyClass> myparam) 

但當我嘗試這樣做時,我有一個編譯器錯誤:

Impossible to convert the first param from MyClass * to std::auto_ptr<_Ty>

爲什麼?感謝您的幫助

編輯1 至於問myparams類型是正常的,但也有一件T PARAM因爲函數是一個模板類

+2

MyFunction中myparams的類型是什麼,它在問題中缺失。 – 2011-02-10 18:16:27

+0

你瞭解`auto_ptr`的用途嗎? – Cascabel 2011-02-10 18:18:21

回答

9

std::auto_ptr<>有一個明確的構造函數,就像任何其他智能指針一樣。這意味着沒有從T*std::auto_ptr<T>的隱式轉換,以防止意外刪除對象。因此,你需要轉換你的原始指出std::auto_ptr<>明確:

MyFunction2(std::auto_ptr<MyClass>(MyFunction())); 

這也是一個好主意,使你的工廠函數返回一個智能指針代替裸指針,它明確給讀者的所有權對象被傳遞給調用者:

static std::auto_ptr<MyClass> MyFunction(myparams) 
{ 
    return std::auto_ptr<MyClass>(new MyClass(myparams)); 
} 
0

有從原始指針的隱式轉換到內部auto_ptr。只要顯式調用出來:

MyFunction2(std::auto_ptr(MyFunction(params)));

注意,分配memoty將在調用後銷燬,以MyFunction2因爲臨時auto_ptr將會消失,重新分配它。

0

您可能要這樣調用的函數MyFunction2 ...

void f() { 
    MyClass* directptr = MyFunction(myparams); 
    std::auto_ptr<MyClass> p(directptr); 
    MyFunction2(p); 
    cout << p.get() << endl; // Prints NULL! 
} 

何wever,當MyFunction2結束時,MyClass實例將被刪除,並且在返回時p將爲NULL,並且directptr將指向已刪除的對象。