0

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]));
Avb Avb
  • 545
  • 2
  • 13
  • 25
  • 1
    yes, it is the right way if you would like to test what your platform does in a case of an undefined behaviour – BЈовић Sep 26 '13 at 13:44
  • 4
    @BЈовић: Where's the undefined behaviour? It looks fine to me, as long as `pktctr` is in range and the pointer is removed before `myobject` is destroyed. Am I missing something? – Mike Seymour Sep 26 '13 at 14:07
  • @MikeSeymour That is lots of assumptions :) I assumed the myobject is on stack in a method, and that it goes out of scope – BЈовић Sep 26 '13 at 14:47

2 Answers2

2

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

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 array
  • the pointer is removed before the end of myobject 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.

JBL
  • 12,588
  • 4
  • 53
  • 84