Reputation: 553
I want to insert a pointer to object into a map. Is this the right way?
object myobject[10];
....
mymap.insert( std::pair<int,object*>(pktctr, &myobject[pktctr]));
Upvotes: 0
Views: 88
Reputation: 254431
Is this the right way?
Yes, although it might read better if you used make_pair
:
mymap.insert(std::make_pair(pktctr, &myobject[pktctr]));
or C++11 syntax:
mymap.insert({pktctr, &myobject[pktctr]});
The only danger is that you must make sure that the pointer is removed, or the map destroyed, before myobject
is destroyed (or, at the very least, make sure that the pointer is never used after that). Otherwise, you'll have a dangling pointer and a whole world of bugs waiting to happen.
Upvotes: 2
Reputation: 12907
This will work and be correct (i.e. not resulting in undefined behavior) as long as one of the following hold:
mymap
and myobject
have the same lifetime (they were declared in the same scope) : you will be sure then that the map outlast the arraymyobject
lifetime (you would have and dangling pointer then, a pointer to something that does not exist anymore)Be sure that pktctr
never get past the end of the array.
Finally, this syntax would also work :
mymap[pktctr] = &myobject[pktctr];
EDIT:
Actually, I am clearing the map in the destructor before myobject is destroyed.
Then you shouldn't have any dangling pointer problem AFAIK.
Upvotes: 2