When can I break the alias rules?

I get this warning. I would like to define the behavior, but I would like to keep this code as it is. When can I break the alias rules?

warning: dereferenced type-guard pointer violates strict anti-aliasing rules [-Wstrict-aliasing]

A string is my own string, which is a POD. This code is called from C. S can be int. String pretty much struct String { RealString*s; } struct String { RealString*s; } , but boilerplate and helper functions. I am making a static statement to make sure String is a module, is 4 bytes and int is 4 bytes. I also wrote a statement that checks if all pointers are> = NotAPtr. Its in my new overload / malloc. I can put this statement in String if you suggest

Given the rules that I follow (basically, this line is a container and always the same size as int) would it be nice if I broke the rules of aliases? Is this one of the few times he violates this right?

 void func(String s) { auto v=*(unsigned int*)&s; myassert(v); if(v < NotAPtr) { //v is an int } else{ //v is a ptr } } 
+4
source share
3 answers

A safe way to treat a variable as two different types is to turn it into a union. One part of the union may be your pointer, and the other may be an integer.

 struct String { union { RealString*s; int i; }; }; 
-1
source

memcpy fully supported. This way is written (then you can use std::copy ).

+4
source

If you cannot change the code to 2 functions, as suggested, why not (it requires the C99 compiler to use uintptr_t - for an older MSVC you need to define it yourself, 2008/2010 should be fine):

 void f(RealString *s) { uintptr_t int = reinterpret_cast<uintptr_t>(s); assert(int); } 
+1
source

Source: https://habr.com/ru/post/1402296/


All Articles