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:
- that instances of myclass held on heap (hence use of new);
- 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
Post a Comment