[英]Pass pointer to auto_ptr with C++
我有一個功能可以做到這一點:
static MyClass* MyFunction(myparams)
{
return new MyClass(myparams)
}
我將能夠在另一個具有以下簽名的函數中調用此函數:
void MyFunction2(std::auto_ptr<MyClass> myparam)
但是當我嘗試執行此操作時,出現編譯器錯誤:
無法將MyClass *的第一個參數轉換為std :: auto_ptr <_Ty>
為什么? 感謝您的任何幫助
編輯1根據要求,myparams類型是正常的,但也有一個T參數,因為該函數在模板類內部
與其他任何智能指針一樣, 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));
}
從原始指針到auto_ptr
沒有隱式轉換。 只需明確指出:
MyFunction2(std::auto_ptr(MyFunction(params)));
請注意,在調用MyFunction2
之后,分配的備忘錄將被銷毀,因為臨時auto_ptr
將消失並取消分配。
您可能想要像這樣調用MyFunction2函數...
void f() {
MyClass* directptr = MyFunction(myparams);
std::auto_ptr<MyClass> p(directptr);
MyFunction2(p);
cout << p.get() << endl; // Prints NULL!
}
但是,當MyFunction2
結束時, MyClass
實例將被刪除,並且在重現p
將為NULL, directptr
將指向已刪除的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.