开发者

Casting a pointer to an int / Storing pointers to type T

开发者 https://www.devze.com 2023-03-25 01:30 出处:网络
I\'m hoping to count how many times a pointer is being used. I have a map: static std::map<unsigned int, unsigned int> counters;

I'm hoping to count how many times a pointer is being used. I have a map:

static std::map<unsigned int, unsigned int> counters;

When I want to insert a new value to it i'm using it like this:

template<class T>
MyClass::addPointer(T * tPtr){
    counters[((unsigned int) tPtr)]++;
}

Is it OK and safe to do a cast like this? It's not an expensive operation etc.?

开发者_StackOverflow中文版Also, is this a suitable way to ensure each pointer only gets one count?

Thanks


IMO, you really don't need to cast it to unsigned int. You can have the map with void*:

static std::map<void*, unsigned int> counters;

Also a null check is important here:

template<class T>
MyClass::addPointer(T * tPtr){
  if(tPtr != 0)
    counters[tPtr]++;
}

Rest is fine.


I suggest that you should keep another map to avoid the cast

map<const volatile void*, unsigned int>


If your compiler supports the C99/C++0x type uintptr_t (defined in stdint.h / cstdint), that is the unsigned integer type specifically for storing pointer values as integers.

Otherwise, pointers can be used as keys themselves, as already mentioned.

0

精彩评论

暂无评论...
验证码 换一张
取 消