我有一些预定义类型继承了 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);
错误是:
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&)’
最佳答案
此版本的insert
通过非常量引用获取键,这意味着您不能使用临时值作为第一个值。这是为了防止内存泄漏;在您的代码中,如果字符串构造函数抛出,temp
将泄漏。
您必须在创建原始指针之前创建键对象:
string key("SomeKey");
any* temp = new whatever;
SomeMap.insert(key, temp);
或者使用 auto_ptr
来确保对象在任何情况下都被删除:
auto_ptr<any> temp(new whatever);
SomeMap.insert("SomeKey", temp);
关于c++ - ptr_map 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3071473/