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]));
有帮助吗?

解决方案

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.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top