Re: casting (void *) to (class *)
On Apr 16, 10:07 am, Maxim Yegorushkin <maxim.yegorush...@gmail.com>
wrote:
On Apr 15, 4:14 pm, Pete Becker <p...@versatilecoding.com> wrote:
Maxim Yegorushkin wrote:
Wow! Why can't it be as simple as:
std::size_t x = v - static_cast<T*>(0);
Because pointer arithmetic is only defined for pointers to
objects in the same array (or one past the end of the
array).
True.
Actually, the original code casts a pointer to an integer,
whereas what I posted is doing a different thing (count of
objects).
Which, of course, fails at compile time if the integral type is
not large enough to hold it. Arguably, on most machines, the
cast to ptrdiff_t should fail (if pointer values are considered
"positive"), since by definition, it won't be large enough. On
a segmented architecture, the conversion to size_t might not
compile either, since size_t might not provide enough room for
the segment. And any number of architectures, different bit
patterns may address the same memory---comparison of pointers
must take this into account, but the conversion to an integral
type may preserve the bit pattern, and comparison of the
resulting integers may take the bits into consideration.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34