I am using the LPARAM (essentially a long, unless we’re on a 64-bit system in which case it is a long long) member of an LVITEM (called lParam) to store a pointer to the object that coincides with that entry in the ListView.
When I want to edit that item, I want to cast that LPARAM to a MyClass*, which works fine so long as the lParam is correctly set to be equal to a MyClass* in the first place, but I’d like to do some kind of checking to make sure it is, in fact, a MyClass that this number is pointing to.
Currently I have this:
LVITEM lv;
// lv is filled in by LVM_GETITEM
classPtr = static_cast<MyClass*>((void*)lv.lParam);
if ( !classPtr )
return false;
Now, I’m not exactly clear: does static_cast return NULL if the argument is not a valid pointer? I assume not, since that’s what dynamic_cast is for, but I’m not entirely certain. And, if I am correct in this assumption, is there any way to check that classPtr is valid before I attempt to access its members and cause a crash…
You can’t check it at all in pure standard C++. You can only do a probabilistic check using the Windows API. So, in practice you can only guarantee it, by making your code correct.
If you could check it you would still not know that it was the correct
MyClassinstance.So, the only good way is to make your code guaranteed correct. That’s easier when you limit access to things. C++ has many features to help you limit access, e.g.
const; use them.Cheers & hth.,