【问题标题】:ptr_map insertingptr_map 插入
【发布时间】:2010-06-18 16:35:42
【问题描述】:

我有一些继承 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&lt;std::basic_string&lt;char&gt;, boost::any&gt;::insert(const char [11], boost::any*&amp;)’


UPD:当我没有将指针传递给任何any temp = any(new KeyEvent());

我明白了:

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

【问题讨论】:

  • 为什么不SomeMap["SomeKey"] = temp;
  • @Cubbi:这将编译,但它不会是异常安全的。如果字符串构造函数或空元素插入抛出,temp 将泄漏。
  • @Mike Seymour:你是对的。这就是我多年来只使用智能指针的结果。

标签: c++ boost types insert boost-ptr-container


【解决方案1】:

此版本的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);

【讨论】:

  • 我喜欢第二种方式,但它会抛出错误:no matching function for call to ‘std::auto_ptr&lt;boost::any&gt;::auto_ptr(NewType*)’
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多