ptr_map插入

Max*_*rai 3 c++ boost types insert boost-ptr-container

我有一些继承boost :: noncopyable的预定义类型(所以我必须将指针存储在这些对象中).我使用boost :: 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);
Run Code Online (Sandbox Code Playgroud)

错误是:

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


UPD:当我没有将指针传递给any时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&)’

Mik*_*our 6

This version of insert takes the key by non-const reference, which means you can't use a temporary as the first value. This is to prevent memory leaks; in your code, temp would leak if the string constructor were to throw.

您必须在创建原始指针之前创建密钥对象:

string key("SomeKey");
any* temp = new whatever;
SomeMap.insert(key, temp);
Run Code Online (Sandbox Code Playgroud)

或使用an auto_ptr来确保删除对象无论发生什么:

auto_ptr<any> temp(new whatever);
SomeMap.insert("SomeKey", temp);
Run Code Online (Sandbox Code Playgroud)