Re: pointer casts(newbie)
On Feb 8, 10:25 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
eminha...@googlemail.com wrote:
would it be possible to cast pointers to any other type of pointer?
for example:
int * a cast to string * b?
Yes, but you could not do anything with the result except for
casting it back. More precisely, the standard guarantees that
when you cast back to the original type, you get the original
value. No other guarantees are made.
That's not quite true. If you cast it to a character type, you
can access the individual bytes. Modifying them will result in
undefined behavior if you later try to use the object with its
original type, but something like:
template< typename T >
void
dump(
std::ostream& dest,
T const& obj )
{
IOSave saver( dest ) ;
dest.setf( std::ios::hex, std::ios::basefield ) ;
dest.fill( '0' ) ;
unsigned char const*current
= reinterpret_cast< unsigned char const* >( &obj ) ;
unsigned char const*end = current + sizeof( T ) ;
while ( current != end ) {
dest << std::setw( 2 ) << *current ;
++ current ;
if ( current != end ) {
dest << ' ' ;
}
}
}
is sometimes useful (and has fully defined behavior).
(Of course, the intent is that an implementation offer
additional guarantees; reinterpret_cast is, or should be, useful
in some very low-level, system specific code, like the
implementation of a garbage collector. But as you said, you
better really know what you're doing if you want to use it. And
exactly what guarantees the implementation offers.)
--
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