2013-10-28 61 views
0

我想寫一個C++類與構造函數需要一個auto_ptr作爲它的參數,這樣我可以從auto_ptr的initialize類實例到另一個實例:構造函數取一個auto_ptr

#include <memory> 

class A 
{ 
public: 
    A() {} 
    A(std::auto_ptr<A> other) {} 
}; 

std::auto_ptr<A> create() 
{ 
    return std::auto_ptr<A>(new A()); 
} 

void foo() 
{ 
    A x = create(); 
    // A y (create()); // works 
} 

g++ -c test.cpp編譯此代碼在GCC 4.6會產生以下錯誤信息:

test.cpp: In function ‘void foo()’: 
test.cpp:17:16: error: no matching function for call to ‘std::auto_ptr<A>::auto_ptr(std::auto_ptr<A>)’ 
test.cpp:17:16: note: candidates are: 
/usr/include/c++/4.6/backward/auto_ptr.h:260:7: note: std::auto_ptr<_Tp>::auto_ptr(std::auto_ptr_ref<_Tp>) [with _Tp = A] 
/usr/include/c++/4.6/backward/auto_ptr.h:260:7: note: no known conversion for argument 1 from ‘std::auto_ptr<A>’ to ‘std::auto_ptr_ref<A>’ 
/usr/include/c++/4.6/backward/auto_ptr.h:125:9: note: std::auto_ptr<_Tp>::auto_ptr(std::auto_ptr<_Tp1>&) [with _Tp1 = A, _Tp = A] 
/usr/include/c++/4.6/backward/auto_ptr.h:125:9: note: no known conversion for argument 1 from ‘std::auto_ptr<A>’ to ‘std::auto_ptr<A>&’ 
/usr/include/c++/4.6/backward/auto_ptr.h:112:7: note: std::auto_ptr<_Tp>::auto_ptr(std::auto_ptr<_Tp>&) [with _Tp = A, std::auto_ptr<_Tp> = std::auto_ptr<A>] 
/usr/include/c++/4.6/backward/auto_ptr.h:112:7: note: no known conversion for argument 1 from ‘std::auto_ptr<A>’ to ‘std::auto_ptr<A>&’ 
test.cpp:7:3: error: initializing argument 1 of ‘A::A(std::auto_ptr<A>)’ 

不過,如果我使用語法A y (create());創建我的對象,它的工作原理。

我想知道爲什麼會發生這種情況,如果有什麼我可以做,以解決它。

編輯:我也指出,如果我改變構造函數簽名

A(const std::auto_ptr<A>& other) {} 

然後一切工作很漂亮,但是這並沒有採取auto_ptr的所有權,因此不具備我想要的語義。

編輯2:如果我做一個賦值操作符一樣的東西,即

A& operator=(std::auto_ptr<A> other) {} 

然後我可以做

A x; 
x = create(); 

爲什麼?

+7

使用'的std :: unique_ptr',而不是'的std :: auto_ptr','的std :: auto_ptr'已被棄用。 – GManNickG

+0

考慮到'create()'返回一個'auto_ptr'就不一定是:'std :: auto_ptr x = create();'? – 2013-10-28 19:10:13

回答

7

您只允許一個隱式的用戶定義轉換。從另一個構造auto_ptr已經涉及通過輔助類auto_ptr_ref的隱式轉換,因此您不能從auto_ptr隱式構造自己的類。

通過使用直接初始化,其中一個轉換是顯式,並且只有一個隱式用戶定義的轉換仍然存在,這很好。爲了「解決」隱式轉換的缺失,您可以修改您的構造函數以使用(非const)引用來代碼auto_ptr,或者將所有內容全部遷移到unique_ptr s。

+0

謝謝,很好的回答。我不知道「只有一個隱式轉換」規則。 C++的黑暗角落。有沒有在線來源? – cfh

+0

@ eriatarka84:如果你仔細想想,這是一個相當明智的規則。如果需要多個轉換,通常無法確定哪個轉換鏈是「正確的」。任何好的入門書都應該描述隱式轉換。 –

+0

這很有趣,我已經使用C++超過15年了,但我不知道介紹性書籍中的所有內容。我想知道這是否說更多關於我或語言。 – cfh

0

用途:

A(std::auto_ptr<A>& other) 
       //^Note the reference! 
{ 
    // Assign interned auto_ptr member here, which you definitely should have 
} 
+2

這不起作用,你不能將臨時對象(作爲從'create()'返回的對象)綁定到非const引用。 – cfh

+0

我一直在談論特別提到的編譯器錯誤。 OP代碼中還有其他錯誤是的! –

+0

還有哪些bug? – cfh

相關問題