c++ - Assigning heap objects to a std::map -


this crashes @ runtime.

std::map<std::string, myclass> mymap; myvalue = new myclass(); mymap["mykey"] = *myvalue; 

i have 2 requirements:

  1. that instances of myclass held on heap (hence use of new);
  2. that able reference these via associative array (hence use of std::map).

why can not use dereference operator succesfully in example? how can fulfill both @ once?

ps. i'm using gcc.

if lose scope of myvalue it's memory leak. it's better store myclass* in map.

std::map<std::string, myclass*> mymap; myvalue = new myclass(); mymap["mykey"] = myvalue; 

in given example, make sure delete element while erasing or removing map<>. can use smart pointer (e.g. boost::shared_ptr) if don't want worry memory management.

also, given example don't know why should crash while dereferencing *myclass. doing weird stuff in copy constructor myclass::myclass(const myclass&) ?


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -