I'm creating unit test for a function that receives a memory address as an unsigned long
Inside the function, this addres is reinterpret_cast
ed into a pointer of one of ur classes.
void my function(Address inputAdress ) // Address comes from: typedef unsigned long Address;
{
ClsMyClassThread* ptr = reinterpret_cast<ClsMyClassThread*>(inputAdress);
if(ptr == nullptr)
{
// Do something
}
}
This function works well, but when creating the UnitTest for it, I can't figure out how can I force ptr
to be nullptr
(I want to test full coverage). When can this happen? Is that even posible?
Thanks!
From reinterpret_cast
conversion point 3 (emphasis mine):
- 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.
So the pedantically correct way to do this (assuming sizeof(Address)
is large enough) is:
myfunction(reinterpret_cast<Address>(static_cast<ClsMyClassThread*>(nullptr)));
whereas the following what some people suggest is not guaranteed to work:
myfunction(0);