将指针强制转换为int类型/将指针存储为T类型

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

本文关键字:类型 指针 存储 int 转换      更新时间:2023-10-16

我希望计算指针被使用的次数。我有一张地图:

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

当我想插入一个新值给它时,我像这样使用它:

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

这样的cast是OK和安全的吗?手术费用不高等等?

此外,这是一个合适的方式来确保每个指针只得到一个计数?

谢谢

依我看,你真的不需要将它强制转换为unsigned int。您可以将mapvoid*结合:

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

null检查在这里也很重要:

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

我建议您保留另一个映射以避免强制转换

map<const volatile void*, unsigned int>

如果您的编译器支持C99/c++ 0x类型uintptr_t(在stdint.h/cstdint中定义),这是专门用于将指针值存储为整数的无符号整数类型。

否则,指针本身可以用作键,如前所述。