我想寫一個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();
爲什麼?
使用'的std :: unique_ptr',而不是'的std :: auto_ptr','的std :: auto_ptr'已被棄用。 – GManNickG
考慮到'create()'返回一個'auto_ptr'就不一定是:'std :: auto_ptr x = create();'? – 2013-10-28 19:10:13
@GManNickG:不幸的是,我沒有奢侈的能夠使用C++ 11。 – cfh