I have a map of auto_ptr's and I am simply trying to set and get map elements but its producing compiler errors. I don't understand what the compiler error means and whats going wrong?
Get compiler error:
[Error] passing 'const std::auto_ptr' as 'this' argument of 'std::auto_ptr<_Tp>::operator std::auto_ptr_ref<_Tp1>() [with _Tp1 = int; _Tp = int]' discards qualifiers [-fpermissive]
Set compiler error:
[Error] no match for 'operator=' (operand types are 'std::map, std::auto_ptr >::mapped_type {aka std::auto_ptr}' and 'int*')
Also I've heard it's not advised to use auto_ptr's in standard c++ library collections (list, vector, map). What kind of smart pointer should I use in the below code?
std::map <std::string, std::auto_ptr<int> > myMap;
// Throws compiler error
std::auto_ptr <int> a = myMap["a"];
// Also throws compiler error
myMap["a"] = new int;
unique_ptr
.auto_ptr
will be removed from C++ soon. – chrisunique_ptr
doesn't work here either (it has deleted copy-assignment) – M.Munique_ptr
may be a reasonable choice, butstd::auto_ptr <int> a = myMap["a"];
should then be updated to e.g.const std::auto_ptr<int>& a = myMap["a"];
, and similarly changes to the pointer should be made using theunique_ptr
API:myMap["a"].reset(new int);
.shared_ptr
's another alternative.... – Tony Delroy