3

I have some predefined type which inherits boost::noncopyable (so I have to store the pointer at these objects). I use a boost::ptr_map. As I know, the second argument in it is already a pointer. So, the code:

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

The error is:

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


UPD: When I don't pass the pointer to the any any temp = any(new KeyEvent());

I get:

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

Oleg Svechkarenko
  • 2,508
  • 25
  • 30
Max Frai
  • 61,946
  • 78
  • 197
  • 306

1 Answers1

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.

You must either create the key object before creating the raw pointer:

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

or use an auto_ptr to ensure that the object is deleted whatever happens:

auto_ptr<any> temp(new whatever);
SomeMap.insert("SomeKey", temp);
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • I like second way but it throws the error: `no matching function for call to ‘std::auto_ptr::auto_ptr(NewType*)’` – Max Frai Jun 18 '10 at 17:28
  • auto_ptr is deprecated, I know it's to be avoided in STL containers, not sure about this boost map. I thought the intention for ptr_map was to pass the value as a pointer – David Bradley Oct 01 '22 at 02:53