Re: Casting void*, comparing void*
On 02/04/2015 09:51 AM, Jens M??ller wrote:
Given the following example code:
class A {
public: A() {}
};
class B {
public; B() {}
; => :
};
A* a = new A();
B* b = new B();
void *aVoid = a;
void *bVoid = b;
bool compareVoid = (aVoid == bVoid); // (1) false?
B* aCastedToB = static_cast<B*> aVoid;
bool compareB = (aCastedToB == b); // (2) false or unspecified?
Unfortunately, I only have access to ISO/IEC 14882:2003 here. Maybe
someone can confirm whether my interpretation of the standard held at
that time, and, more importantly, whether it still holds for the current
version of the standard.
Re (2): Section 5.2.9 [expr.static.cast], ?? 10 says that a pointer to
cv1 void can be cast into an arbitrary pointer to cv2 T (with cv2 >=
cv1).
Not quite arbitrary: "If the original pointer value represents
the address A of a byte in memory and A satisfies the alignment
requirement of T, then the resulting pointer value represents the same
address as the original pointer value, that is, A. The result of any
other such pointer conversion is unspecified."
... Converting a pointer to void* and back to the original type will
yield the original value. Do I understand correctly that the standard
leaves open the result (and maybe also the behaviour?!) when the target
type of the cast is _not_ the original type? In particular: Is it
possible to make any statement about the result of equal-comparing a
pointer obtained in such a way with another pointer that "really" is of
that type?
Two pointers compare equal if "both represent the same address (3.9.2)"
(5.10p2). However, if the clause cited earlier leads to the conclusion
that "the result of ... such pointer conversion is unspecified", you
cannot, in particular, justify making any assumptions about which
address "static_cast<B*> aVoid" represents. There's no reason to expect
A and B to have different alignment requirements - but in the more
general case, where both classes have meaningfully different lists of
non-static members, it's quite possible for them to have different
alignment requirements. If so, 'a' might not be correctly aligned to
allow aVoid to be converted to a B*.
Re (1): Regarding pointer comparisons, Section 5.9 [expr.eq] says: "Two
pointers of the same type compare equal if and only if they are both
null, both point to the same function, or both represent the same
address (3.9.2). This guarantees that the comparison in the example code
will yield false, right?
Yes.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]