c++ - ptr_map 插入

标签 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);

错误是:

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/

相关文章:

python - 更改 python 函数参数的类型而不重新绑定(bind)

C++ - 检测越界访问

c++ - 从 C++ 中的私有(private)模板类继承构造函数

c++ - 为可变参数模板类专门化零个模板参数和一个模板参数版本

c++ - boost asio - 来自一个线程的 SSL async_read 和 async_write

java - 性能偏执狂 : how much expensive are Float. parseFloat(String), Integer.parseInt(String)?

c++ - c++中三元运算符的副作用和返回类型是什么?

c++ - 我的程序找不到boost库

c++ - 什么是 boost::ptr_vector::pop_front() 返回类型?

inheritance - 使用函数式编程风格数据类型的模型继承