c++ - Casting between primitive type pointers -
c++ - Casting between primitive type pointers -
is next well-defined:
char* charptr = new char[42]; int* intptr = (int*)charptr; charptr++; intptr = (int*) charptr; the intptr isn't aligned (in @ to the lowest degree 1 of 2 cases). illegal having there? ub using @ stage? how can utilize , how can't you?
first, of course: pointer guaranteed aligned in first case (by §5.3.4/10 , §3.7.4.1/2), , may correctly aligned in both cases. (obviously, if sizeof(int) == 1, when not case, implementation doesn't have alignment requirements.)
and create things clear: casts reinterpret_cast.
beyond that, interesting question, because far can tell, there no difference in 2 casts, far standard concerned. results of conversion unspecified (according §5.2.10/7); you're not guaranteed converting char* result in original value. (it won't, example, on machines int* smaller char*.)
in practice, of course: standard requires homecoming value of new char[n] sufficiently aligned value may fit it, guaranteed able do:
intptr = new (charptr) int; which has same effect cast, given default constructor int no-op. (and assuming sizeof(int) <= 42.) it's hard imagine implementation in first part fails. should able utilize intptr other legally obtained intptr. , thought converting char* somehow result in different value original char* seems preposterous.
in sec part, bets off: can't dereference pointer (unless implementation guarantees otherwise), , it's quite possible converting char* results in different. (imagine word addressed machine, example, converting char* int* rounds up. converting result in char* sizeof(int) higher original. or effort convert misaligned pointer resulted in null pointer.)
c++ language-lawyer strict-aliasing
Comments
Post a Comment