强制 reinterpret_cast 到 return nullptr

Force reinterpret_cast to return nullptr

我正在为接收内存地址作为 unsigned long

的函数创建单元测试

在函数内部,这个地址被 reinterpret_casted 到你的 类 之一的指针中。

void my function(Address inputAdress ) // Address comes from: typedef unsigned long Address;
{
  ClsMyClassThread* ptr = reinterpret_cast<ClsMyClassThread*>(inputAdress);

  if(ptr == nullptr)
  {
    // Do something 
  }
}

这个函数运行良好,但是在为其创建 UnitTest 时,我不知道如何强制 ptrnullptr(我想测试全覆盖)。这什么时候可以发生?这可能吗?

谢谢!

来自 reinterpret_cast conversion 第 3 点(强调我的):

  1. A value of any integral or enumeration type can be converted to a pointer type. A pointer converted to an integer of sufficient size and back to the same pointer type is guaranteed to have its original value, otherwise the resulting pointer cannot be dereferenced safely (the round-trip conversion in the opposite direction is not guaranteed; the same pointer may have multiple integer representations) The null pointer constant NULL or integer zero is not guaranteed to yield the null pointer value of the target type; static_cast or implicit conversion should be used for this purpose.

所以迂腐的正确方法(假设 sizeof(Address) 足够大)是:

myfunction(reinterpret_cast<Address>(static_cast<ClsMyClassThread*>(nullptr)));

而以下一些人的建议保证有效:

myfunction(0);

这些很可能会起作用:

my_function(NULL);
my_function(0);
Address a = 0;
my_function(a);

尽管技术上绝对正确,您需要:

my_function(reinterpret_cast<Address>(static_cast<ClsMyClassThread*>(nullptr)));

(标准保证从零到指针类型的转换是空指针值,仅当涉及的零是直接文字表达式时,而不是诸如 inputAdress 之类的变量恰好具有零值。所以相反,这使用了两个反 reinterpret_cast 表达式的保证。)