Re: Does this memory access yield undefined behaviour?
"litb" <Schaub-Johannes@web.de> schrieb im Newsbeitrag
news:7ae1bd49-c12e-4e9d-87ce-fc2476060fa2@c9g2000yqm.googlegroups.com...
I believe that for PODs you can always use the following well-defined
pattern (again, assuming all the alignment requirements are
satisfied):
static_cast<pod2_t*>(static_cast<void*>(&pod1));
I would like to get a reference to the appropriate Standard section
please. This looks interesting.
According to 3.9.2/4, a void pointer shall be able to hold any object
pointer. In addition, 4.10/2 says that a pointer to any object type can be
converted to a void pointer and that the result is a pointer to the start of
the storage location where the object resides. This is confirmed by 3.9.2/4,
which furthermore says that a pointer to void shall have the same
representation and alignment requirements as a pointer to char. The
conversion from pointer to object to pointer to void can be done implicitly
or using a static_cast (5.2.9/4).
As far as casting from pointer to void to pointer to object is concerned,
the standard only guarantees that casting from T* to void and back to T*
will work (5.2.9/10). However, an exception for char which is scattered all
over the standrad, but most of it can be found in 3.9 and has to do with the
basic properties of objects being storage regions. Also note that there is
confusion whether unsigned char or just plain char should be used to access
memory, because plain char might be signed or unsigned, and in the former
case certain bit patterns might be adjusted when the memory is accessed. The
following two postings might be interesting for you:
http://groups.google.com/group/comp.lang.c++.moderated/msg/81b1187f784d7274
http://groups.google.com/group/comp.lang.c++.moderated/msg/aa874558058b127c
Anyway, its seems like you can cast from a T* to a char* with the following
two convenience functions:
// Converts a pointer of any non-const
// type to a non-const char pointer.
inline char* char_ptr( void* p ) throw()
{ return static_cast<char*>( p ); }
// Converts a pointer of any constant
// type to a constant char pointer.
inline const char* char_ptr( const void* p ) throw()
{ return static_cast<const char*>( p ); }
--
Matthias Hofmann
Anvil-Soft, CEO
http://www.anvil-soft.com - The Creators of Toilet Tycoon
http://www.anvil-soft.de - Die Macher des Klomanagers
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]