2015-09-05 43 views
0

我仍在探索C++ 11.所以我很確定我做錯了什麼。但我無法弄清楚問題所在。將auto_ptr分配給weak_ptr

我有以下代碼:

MyClass::MyClass(const PlayerEventListener* eventListener) 
{ 
    weak_ptr<PlayerEventListener> _listener; 
    std::auto_ptr<PlayerEventListener> autoPtr; 
    autoPtr.reset(const_cast<PlayerEventListener*> (eventListener)); 
    // I get error for this line 
    _listener = autoPtr; 
} 

我得到以下錯誤:沒有可行的重載 '='

但下面的代碼編譯罰款:

MyClass::MyClass(const PlayerEventListener* eventListener) 
{ 
    weak_ptr<PlayerEventListener> _listener; 
    std::shared_ptr<PlayerEventListener> sharedPtr; 
    sharedPtr.reset(const_cast<PlayerEventListener*> (eventListener)); 
    // I get error for this line 
    _listener = sharedPtr; 
} 

有人可以解釋爲什麼我無法將自動指針轉換爲弱指針?

+1

'auto_ptr'沒有引用計數器,一個'weak_ptr'會被觀察到 –

+1

在std :: auto_ptr在C++ 11中被棄用,基本上是一個'std :: unique_ptr',你不能複製一個unique_ptr。 –

+1

「我很確定我做錯了什麼」 - 是的,您正在使用'auto_ptr' –

回答

0

weak_ptr是一個對象,它保存對shared_ptr而不是auto_ptr實際保存的對象的安全引用。因此,沒有任何超載的operator=可以在weak_ptr的實現中提供分配auto_ptrweak_ptr。它可以通過編譯this example code,看着錯誤

In constructor 'MyClass::MyClass(const PlayerEventListener*)': 
21:14: error: no match for 'operator=' (operand types are 'std::weak_ptr<PlayerEventListener>' and 'std::auto_ptr<PlayerEventListener>') 

驗證只需記住:根據http://www.cplusplus.com/reference/memory/auto_ptr/

This class template (auto_ptr) is deprecated as of C++11. unique_ptr is a new facility with a similar functionality, but with improved security (no fake copy assignments), added features (deleters) and support for arrays. See unique_ptr for additional information.

+1

不贊成使用'std :: auto_ptr',但並不回答這個問題! –

+0

@πάνταῥεῖ更新回答問題。 – PiotrSliwa