Get a persistent pointer to an object in a list
I am currently looking for a way to have a constant pointer to an object inside a list. By constant I mean a pointer that always points to the same object as long as it exists.
I couldn't find any easy way to do this, so does anyone have an idea? I am already using boost, so the boost solution is also very acceptable.
To shed more light on what I need, here's an example:
std::map<int, std::list<void (*)()> > handlerList; // I store some callback functions like this
void addHandler( int id, void (*handlerFunc)() ) {
handlerList[id].push_back(handlerFunc); // 100% intended behavior (I know that the []-operator creates a object if it doesn't exist)
}
What I would like is something like this:
some_permanent_pointer_type addHandler( int id, void (*handlerFunc)() ) {
return handlerList[id].push_back(handlerFunc);
}
And then at some other point:
some_permanent_pointer_type handlerPointer;
handlerPointer = addHandler( 123, someFunc );
// Other point of code
handlerPointer.delete(); // or
ListType.delete(handlerPointer); // Or something like this
Does anyone have any ideas? Writing your own class wouldn't be such a deal. But I have no idea how to implement this. But I would prefer something that already exists. Time and stuff.
Note. This code will work on a Linux machine.
source to share
Here's something I quickly threw together. Currently calling destroy()
twice is bad, but this is the fix.
#include <map>
#include <list>
std::map<int, std::list<void (*)()> > handlerList;
class HandleHandle {
public:
HandleHandle(std::list<void (*)()> &list, std::list<void (*)()>::iterator iterator):
list_(list),
iterator_(iterator)
{}
void destroy() {
list_.erase(iterator_);
}
private:
std::list<void (*)()> & list_;
std::list<void (*)()>::iterator iterator_;
};
HandleHandle addHandler(int id, void (*handlerFunc)()) {
handlerList[id].push_back(handlerFunc);
return HandleHandle(handlerList[id], handlerList[id].rbegin().base());
}
void someFunc() {
}
int main() {
auto handlerPointer = addHandler(123, someFunc);
handlerPointer.destroy();
}
source to share
Of the requirements you have specified, you need no more than
using funclist = std::list<void (*)()>;
std::map<int, funclist > handlerList; // I store some callback functions like this
funclist& addHandler( int id, void (*handlerFunc)() ) {
handlerList[id].push_back(handlerFunc); // Creates list on demand
return handlerList[id];
}
auto list5 = addHandler(5, &foo);
addHandler(5, &bar);
list5.clear(); // Clears entire handlerList[5], i.e. &foo and &bar.
source to share