2010-06-18 52 views
3

我有一些預定義類型繼承boost :: noncopyable(所以我必須將指針存儲在這些對象)。我使用boost :: ptr_map。據我所知,其中的第二個參數已經是一個指針。所以,代碼:ptr_map插入

ptr_map<string, boost::any> SomeMap; 
typedef %Some noncopyable class/signature% NewType; 

// Inserting now 
boost::any *temp = new boost::any(new KeyEvent()); 
SomeMap.insert("SomeKey", temp); 

的錯誤是:

error: no matching function for call to ‘boost::ptr_map<std::basic_string<char>, boost::any>::insert(const char [11], boost::any*&)’


UPD:當我不指針傳遞到任何any temp = any(new KeyEvent());

我得到:

error: no matching function for call to ‘boost::ptr_map<std::basic_string<char>, boost::any>::insert(const char [11], boost::any&)’

+2

爲什麼不'SomeMap [」 SomeKey「] = temp;'? – Cubbi 2010-06-18 17:36:25

+1

@Cubbi:會編譯,但它不會是異常安全的。如果字符串構造函數或空元素插入拋出,'temp'將會泄漏。 – 2010-06-19 20:03:45

+0

@Mike Seymour:你說得對。這就是我幾年來只使用智能指針的原因。 – Cubbi 2010-06-20 18:12:25

回答

6

此版本的insert通過非const引用獲取密鑰,這意味着您不能使用臨時值作爲第一個值。這是爲了防止內存泄漏;在你的代碼中,temp會在字符串構造函數拋出時泄漏。

必須要麼創建原始指針之前創建的關鍵對象:

string key("SomeKey"); 
any* temp = new whatever; 
SomeMap.insert(key, temp); 

或使用auto_ptr以確保對象被刪除無論發生什麼:

auto_ptr<any> temp(new whatever); 
SomeMap.insert("SomeKey", temp); 
+0

我喜歡第二種方式,但它引發錯誤:'沒有匹配函數調用'std :: auto_ptr :: auto_ptr(NewType *)'' – Ockonal 2010-06-18 17:28:29