- "... casting object addresses to char* pointers and then performing pointer arithmetic on them almost always yields undefined behavior"
-
class Foo;
...
Foo* foo_ptr = new Foo;
char* char_ptr = reinterpret_cast<char*>(foo_ptr);
Quote:The point of that statement is that given a pointer, you can't make assumptions about it. Unless you know that you have aI agree with that statement, although I don't think you've given good examples. Of course advancing an array of type X with sizeof(Y) bytes where sizeof(X) != sizeof(Y) would result in an error. The idea behind the pointer arithmetic after converting to char* is that you generally can't do things like
POD type pointer, you could randomly trash data by manipulating it. That stands for any cast, the only point of saying "to char *"
specificly is to emphesize that when you decide to throw out all information regarding your pointers you break things.
struct A{ short sh; char byte; int n;};A a;char* p = (char*)&ap += sizeof( short ) + sizeof( char );*((int*)p) = 5; // We're probably not assigning to n
Quote:Original post by thedustbustr
I can't find the reference in Effective C++ Vol 3, could you look it up for me?
Quote:Original post by Mike.PopoloskiQuote:Original post by thedustbustr
I can't find the reference in Effective C++ Vol 3, could you look it up for me?
Yes, I don't remember that one being in the latest version (the one I own). Maybe it was one of the ones he removed, which would show that the item may not be important / valid.
Quote:Original post by fpsgamer
That quote caused me confusion because for example, casting to char is pretty much the only way to write objects to disk isn't it?
Quote:Original post by fpsgamer
casting to char is pretty much the only way to write objects to disk isn't it?
Quote:Original post by Extrarius
Any use of 'reinterpret_cast' involves at least implementation-defined behavior. The only specified behavior is that casting to a different type and then casting back to the first type must, in many cases, give back the original value. Other than that, the behavior is unspecified.
In other words, any useful code that uses reinterpret_cast is making assumptions about the implementation it is being compiled under.