map<string, int*> map;
int i = 10;
int j = 15;
map.emplace("one", &i);
map.emplace("two", &j);
map.clear();
What I'm asking is, is using std::map::clear() sufficient enough to prevent memory leaks or memory errors when storing those pointers? Does it deallocate data? Does it set the pointer to nullptr?
Or should I use an iterator to iterate through the map to do this all myself?
It does not deallocate the data that is pointed to by the int*
> Or should I use an iterator to iterate through the map to do this all myself?
You should use a std::map< std::string, std::vector<int> > instead, and save yourself a whole lot of trouble; in this case, the map would take care of all memory management.
EDIT: In the code snippet that you posted, there is no memory leak: the integers i and j are not allocated dynamically.
You should use a std::map< std::string, std::vector<int> > instead, and save yourself a whole lot of trouble; in this case, the map would take care of all memory management.
Hmm... I'm only wanting to store one value at each map position though. How does this make the map handle the memory management?
class Holder
{
public:
void Load(const Held* _h, string _key)
{
objects.emplace(key, _h);
}
map<string, Held*> objects;
};
class Held
{
/* ... */
};
int main()
{
Holder holder;
Held held;
holder.Load("one", &held);
// This is just so Holder can render and update the values
// inside of Held, but the user can still maintain control of
// what Held does from the outside.
}
EDIT: This is still very simplified, but it's gets across the general idea. I really just want to make sure I don't leave any stray pointers pointing to some random memory positions. Haha.
The map would then just keep a pointer to Held. If the pointed Held object was allocated using new, the map would not release it. If it was not, as in the code above, there is no issue.
How is the Held object created? Held held; as in your code? There is no issue.
Or Held* h = new Held( /* ... */ ) ; ? Someone would have to delete it eventually, and that someone is not the map.
Once more question, will the map clear any references from the pointers inside of it. As in, will it set them to nullptr to make sure there aren't any "dangling pointers"?