How to properly delete a map of pointers as key? - c++

I have a map of key/value pointers :
std::map<A*, B*> myMap;
What would be the proper way to liberate the memory of the key only?
I was thinking about doing this :
for (auto itr = _myMap.begin(); itr != _myMap.end(); itr++)
{
if (certainCondition == true)
{
delete itr->first;
itr->first = nullptr;
}
}
Is it the correct way of doing it? Will my map keep nullptr as a key and future iteration will include nullptr?

You cannot modify the key of the container because it is used to define the ordering and changing it in place could invalidate the ordering. Furthermore, each key needs to be unique. Therefore, you need to remove the item from the map then clean up the memory.
If you already have the key:
myMap.erase(key);
delete key;
If you already have an iterator within the map:
A* keyCopy = itr->first;
myMap.erase(itr);
delete keyCopy;
Edit
Per your updated question:
auto itr = myMap.begin();
while (itr != myMap.end())
{
if (certainCondition == true)
{
A* keyCopy = itr->first;
itr = myMap.erase(itr);
delete keyCopy;
}
else
{
++itr;
}
}

erase() the element from the map, then delete the pointer that was acting as the key (if necessary, cached the pointer before the erase, if it does not exist anywhere else)
A map can only have one occurrence of each unique key. Even if it were possible - what would happen if you wanted to nullptr out more than one of the elements' keys? Nothing useful!

The key is const. You should not be able to change it.
http://www.cplusplus.com/reference/map/map/

Related

How to insert data into map where one parameter is an object?

I have a class Normal defined as:
class Normal
{
bool value;
float time;
public:
Normal(bool val,float time): value(val),time(time) {}
}
Also, I have declared a map variable as:
map<string,Normal> myMap;
Now I want to insert an data into this map.
Is this way of inserting correct?
Normal temp(true,45.04);
myMap.insert(pair<string,Normal>("one",temp));
or
myMap["one"]=temp;
How should i insert data into the map?
In C++03 :
myMap.insert(std::make_pair(
"one",
Normal(true, 45.04)
));
In C++11 :
m.emplace(std::piecewise_construct,
std::forward_as_tuple("one"),
std::forward_as_tuple(true, 45.04)
);
Both avoid default-constructing a key-value pair inside operator[] and then overwriting it.
Use this code
Normal *temp = new Normal(true,45.9);
mymap.insert(make_pair("one",temp));
avoid shallow copy since pointer is involved.
EDIT: Use insert function to insert data in map. Index is not the best way. specially when u r accessing
See this link for details
In STL maps, is it better to use map::insert than []?
EDIT2: For deletion,use the below code.
for(std::map<string, Normal*>::iterator itr = mymap.begin();it != mymap.end();)
{
if(it->second != NULL)
{
delete (it->second);
(it->second) = NULL;
it=mymap.erase(it);
}
else
{
++it;
}
}

C++ map, find element and insert it into another map (without copying)

How to correctly find element from source map and insert it into another map?
std::map<int, std::shared_prt<Obj>> src_map
std::map<int, std::shared_prt<Obj>> target_map
int key = 6;
auto found_elem = src_map.find(key);
if (found_elem != src_map.end()) {
if (target_map.find(key) == target_map.end()) {
target_map.insert(found_elem ); <---- How to correctly insert found element from src_map to target_map
}
}
target_map.insert(found_elem);
found_elem is an iterator, you need to insert the value it refers to:
target_map.insert(*found_elem);
Also this could be done more efficiently:
if (target_map.find(key) == target_map.end()) {
target_map.insert(found_elem);
}
You do the lookup twice. Once in find and again in insert.
It's better to just try to insert it, and if you need to know whether it was inserted check the return value:
auto inserted = target_map.insert(*found_elem);
// inserted.first is the iterator to the element with the desired key
// inserted.second is true if a new element was inserted, false if the key already existed
Other options for putting it in the map are to find the position where it belongs, then insert at that position if it's not there already:
auto lower = target_map.lower_bound(key);
if (lower == target_map.end() || lower->first != key) {
target_map.insert(lower, *found_elem);
}
Another option is:
auto& val = target_map[found_elem->first];
if (!val)
val = found_elem->second;
but this is not exactly the same, because if the key already exists in the map with an empty shared_ptr as the value then the value will get replaced. Depending whether you can have empty shared_ptr objects in the map that might not be correct for your program.
Yet another, with slightly different meaning again, is:
target_map[found_elem->first] = found_elem->second;
In current declaration
std::map<int, Obj> src_map
std::map<int, Obj> target_map
You can't have one Obj instance in memory connected to both maps. Either you remove Obj from src_map and put in target_map or change declaration to;
std::map<int, Obj*> src_map
std::map<int, Obj*> target_map
or any other pointer type (shared_ptr as suggested in comment), without this you will always have two independent objects in memory.

why does returning a map.insert().second introduce unreachable memory?

The following code:
~A()
{
for (itr = mymap.begin(); itr != mymap.end() ++itr)
{
delete itr->second //the map look like this <std::string , T*>
}
}
A::Addnew(std::string name)
{
return mymap.insert(std::pair<std::string,T*>(name, new T)).second;
}
introduces a memory leak, but if I change the AddNew() member function to:
itr = mymap.find(name);
if(itr == mymap.end())
{
return mymap.insert(std::pair<std::string,T*>(name, new T)).second;
}
then there is no memory leak.
It seems like if I called the first case accidentally, I will introduce lots of new T, but my mymap.size() cannot keep track of it. Can anyone explain this?
std::map::insert() is a no-op if the key already exists in the map.
If you try to insert a duplicate key, the first version of your code will leak the object it has allocated using new.
The second version does not have this problem since you don't call new unless you've established that the key doesn't exist in the map.
Two good ways to fix the leak are:
store the objects by value;
store smart pointers to objects.
In your first AddNew function:
when you are inserting a member whose key have existed in the map,
you will create a T object,but you do not release it:
you can do like this:
A::Addnew(std::string name)
{
T *temp = new T;
if(mymap.insert(std::pair<std::string,T*>(name, temp)).second)
return true;
else
{
delete temp;
return false;
}
}

c++ process scheduling questions

I am working on code which implements a Multilevel Feedback Queue Scheduler. There is something not clear in a part of the code:
void Scheduler_MFQS :: fill_queue(int clk) {
list<Process>::iterator itr;
for(itr = processes.begin(); itr != processes.end(); itr++) {
if((itr -> has_arrived(clk)) && (!queues[0].contains(*itr))) {
Process tmp (*itr);
queues[0].add_process(tmp);
remove(processes.begin(), processes.end(), *itr);
}
}
}
What this basically does is just put the process into the base queues under some condition. But i don't know what Process tmp (*itr); means? However, it compiles legally. Does that mean create a Process object called tmp? But what is the next, iterator (*itr) mean in c++?
"Process tmp (*itr);" mean?
It calls Process(const Process& &) copy constructor to create tmp object;
what is the next, iterator (*itr) mean in c++?
itr is std::list::iterator type, it's a pointer to current list node. *itr is getting the content of itr, which is a Process.
Your code can enhance a bit, demo as below:
// list<Process>::iterator itr; // move this into for loop, narrow variable scope and lifetime
/*auto if C++11*/
processes.unique(); // you actually only want unique processes from list
for(list<Process>::iterator itr = processes.begin(); itr != processes.end(); ++itr)
^^ call preincrement, faster
{
if((itr -> has_arrived(clk)) /*&& (!queues[0].contains(*itr))*/) {
^^ process list contains unique item only, no need to compare
//Process tmp (*itr); comment out this line, save one object copy
queues[0].add_process(*itr);
//remove(processes.begin(), processes.end(), *itr);
// You don't need to clear item in the loop
}
}
processes.clear(); // or swap with an empty list
// std::list<Process> p2;
// p2.swap(ps);
itr is the iterator which points to some container element(list in your case). When you use asterisk(*) on iterator you gain access to its content i.e. to the actual element of the list. In your case it is a Process object.

C++ map iteration with deletion

I couldn't find an instance of how to do this, so I was hoping someone could help me out. I have a map defined in a class as follows:
std::map<std::string, TranslationFinished> translationEvents;
TranslationFinished is a boost::function. I have a method as part of my class that iterates through this map, calling each of the functions like so:
void BaseSprite::DispatchTranslationEvents()
{
for(auto it = translationEvents.begin(); it != translationEvents.end(); ++it)
{
it->second(this);
}
}
However it's possible for a function called by it->second(this); to remove an element from the translationEvents map (usually itself) using the following function:
bool BaseSprite::RemoveTranslationEvent(const std::string &index)
{
bool removed = false;
auto it = translationEvents.find(index);
if (it != translationEvents.end())
{
translationEvents.erase(it);
removed = true;
}
return removed;
}
doing this causes a debug assertion fail when the DispatchTranslationEvents() tries to increment the iterator. Is there a way to iterate through a map safely with the possibility that a function call during the iteration may remove an element from the map?
Thanks in advance
EDIT: Accidently C/Pd the wrong Remove Event code. Fixed now.
map::erase invalidates the iterator being deleted (obviously), but not the rest of the map.
This means that:
if you delete any element other than the current one, you're safe, and
if you delete the current element, you must first get the next iterator, so you can continue iterating from that (that's why the erase function for most containers return the next iterator). std::map's doesn't, so you have to do this manually)
Assuming you only ever delete the current element, then you could simply rewrite the loop like this:
for(auto it = translationEvents.begin(); it != translationEvents.end();)
{
auto next = it;
++next; // get the next element
it->second(this); // process (and maybe delete) the current element
it = next; // skip to the next element
}
Otherwise (if the function may delete any element) it may get a bit more complicated.
Generally speaking it is frowned upon to modify the collection during iteration. Many collections invalidate the iterator when the collection is modified, including many of the containers in C# (I know you're in C++). You can create a vector of events you want removed during the iteration and then remove them afterwards.
After reading all other answers, I am at an advantage here... But here it goes.
However it's possible for a function called by it->second(this); to remove an element from the translationEvents map (usually itself)
If this is true, that is, a callback can remove any element from the container, you cannot possibly resolve this issue from the loop itself.
Deleting the current callback
In the simpler case where the callback can only remove itself, you can use different approaches:
// [1] Let the callback actually remove itself
for ( iterator it = next = m.begin(); it != m.end(); it = next ) {
++next;
it->second(this);
}
// [2] Have the callback tell us whether we should remove it
for ( iterator it = m.begin(); it != m.end(); ) {
if ( !it->second(this) ) { // false means "remove me"
m.erase( it++ );
} else {
++it;
}
}
Among these two options, I would clearly prefer [2], as you are decoupling the callback from the implementation of the handler. That is, the callback in [2] knows nothing at all about the container in which it is held. [1] has a higher coupling (the callback knows about the container) and is harder to reason about as the container is changed from multiple places in code. Some time later you might even look back at the code, think that it is a weird loop (not remembering that the callback removes itself) and refactor it into something more sensible as for ( auto it = m.begin(), end = m.end(); it != end; ++it ) it->second(this);
Deleting other callbacks
For the more complex problem of can remove any other callback, it all depends on the compromises that you can make. In the simple case, where it only removes other callbacks after the complete iteration, you can provide a separate member function that will keep the elements to remove, and then remove them all at once after the loop completes:
void removeElement( std::string const & name ) {
to_remove.push_back(name);
}
...
for ( iterator it = m.begin(); it != m.end(); ++it ) {
it->second( this ); // callback will possibly add the element to remove
}
// actually remove
for ( auto it = to_remove.begin(); it != to_begin.end(); ++it ) {
m.erase( *it );
}
If removal of the elements need to be immediate (i.e. they should not be called even in this iteration if they have not yet been called), then you can modify that approach by checking whether it was marked for deletion before executing the call. The mark can be done in two ways, the generic of which would be changing the value type in the container to be a pair<bool,T>, where the bool indicates whether it is alive or not. If, as in this case, the contained object can be changed you could just do that:
void removeElement( std::string const & name ) {
auto it = m.find( name ); // add error checking...
it->second = TranslationFinished(); // empty functor
}
...
for ( auto it = m.begin(); it != m.end(); ++it ) {
if ( !it->second.empty() )
it->second(this);
}
for ( auto it = m.begin(); it != m.end(); ) { // [3]
if ( it->second.empty() )
m.erase( it++ );
else
++it;
}
Note that since a callback can remove any element in the container, you cannot erase as you go, as the current callback could remove an already visited iterator. Then again, you might not care about leaving the empty functors for a while, so it might be ok just to ignore it and perform the erase as you go. Elements already visited that are marked for removal will be cleared in the next pass.
My solution is to first create a temporary container, and swap it with the original one. Then you can iterator through the temporary container and insert the ones you want to keep to the original container.
void BaseSprite::DispatchTranslationEvents()
{
typedef std::map<std::string, TranslationFinished> container_t;
container_t tempEvents;
tempEvents.swap(translationEvents);
for(auto it = tempEvents.begin(); it != tempEvents.end(); ++it)
{
if (true == it->second(this))
translationEvents.insert(it);
}
}
And the TranslationFinished functions should return true if it want to be keeped and return false to get removed.
bool BaseSprite::RemoveTranslationEvent(const std::string &index)
{
bool keep = false;
return keep;
}
There should be a way for you to erase a element during your iteration, maybe a little tricky.
for(auto it = translationEvents.begin(); it != translationEvents.end();)
{
//remove the "erase" logic from second call
it->second(this);
//do erase and increase the iterator here, NOTE: ++ action is very important
translationEvents.erase(it++);
}
The iterator will be invalid once the element is removed, so you can not use that iterator to do increase action anymore after you remove it. However, remove an element will not affect other element in map implementation, IIRC. So suffix ++ will copy the iter first and increase the iterator right after that, then return the copy value, which means iterator is increased before erase action, this should be safe for you requirement.
You could defer the removal until the dispatch loop:
typedef boost::function< some stuff > TranslationFunc;
bool BaseSprite::RemoveTranslationEvent(const std::string &index)
{
bool removed = false;
auto it = translationEvents.find(index);
if (it != translationEvents.end())
{
it->second = TranslationFunc(); // a null function indicates invalid event for later
removed = true;
}
return removed;
}
protect against invoking an invalid event in the loop itself, and cleanup any "removed" events:
void BaseSprite::DispatchTranslationEvents()
{
for(auto it = translationEvents.begin(); it != translationEvents.end();)
{
// here we invoke the event if it exists
if(!it->second.empty())
{
it->second(this);
}
// if the event reset itself in the map, then we can cleanup
if(it->second.empty())
{
translationEvents.erase(it++); // post increment saves hassles
}
else
{
++it;
}
}
}
one obvious caveat is if an event is iterated over, and then later on deleted, it will not get a chance to be iterated over again to be deleted during the current dispatch loop.
this means the actual deletion of that event will be deferred until the next time the dispatch loop is run.
The problem is ++it follows the possible erasure. Would this work for you?
void BaseSprite::DispatchTranslationEvents()
{
for(auto it = translationEvents.begin(), next = it;
it != translationEvents.end(); it = next)
{
next=it;
++next;
it->second(this);
}
}