> On 2015–10–02, at 8:21 PM, Vlad from Moscow <
vlad....@mail.ru> wrote:
>
> So if I write a similar function
>
> void * my_memset( void *, int, size_t );
>
> when the compiler will read my description of the function somewhere and behave accordingly in the same way as with the memset?
Eh… please don’t extrapolate from any speculations about what is or isn’t likely to aggravate a UB condition.
> Or if I write
>
> int x = 10;
> int y = x;
>
> int *p = ( int * )std::memset( &x, 0, sizeof( x ) );
>
> *p = 20;
>
> if ( x == y )
> return true;
> else
> return false;
>
> I will get true?
No, there’s nothing wrong with either of those assignments. You cleared the object representation of x, then restored the value of &x back to its rightful type int*, then used that to legally assign a new value of 20. No problems, the answer is false.
> And one more example of undefined behaviour
>
> int x = 10;
> int y = x;
>
> int *p = static_cast<int *>( static_cast<void *>( &x ) );
> *p = 20;
>
> if ( y == x )
> {
> std::cout << "True" << std::endl;
> std::cout << "x = " << x << ", y = " << y << std::endl;
> }
> else
> {
> std::cout << "False" << std::endl;
> std::cout << "x = " << x << ", y = " << y << std::endl;
> }
Again, casting to void* and then back to int* is fine.
The only way you get a problem from an X* pointer with a referent of unrelated type Y is if the compiler makes an invalid assumption that a Y can never be reached from an X*. I don’t know enough about alias analysis… I can’t say whether such assumptions are commonplace and difficult to avoid, or if they would be regarded compiler bugs, or if in reality they no longer exist. See the end of the recent thread, “[class.mem]/19 and writing to common initial sequence members.” Jens Maurer says, “Having two seemingly type-unrelated pointers alias is totally unhelpful.” My impression is that the strict aliasing rule is imperfect, but you should be OK as long as you restrict function parameters and globals to void* or [unsigned] char* when the referent type is not as listed in the rule, [basic.lval] §3.10/10.