This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: strict aliasing: cast from char[] or char *


On Tue, Jun 7, 2011 at 5:51 AM, Herman, Geza <geza@bitquad.com> wrote:
> Hi,
>
> Sorry, if it has been discussed before, I found a lot of information on
> strict aliasing in gcc, but nothing about this particular case. ?I'd like to
> code a custom container class: it has a char[] (or dynamically allocated
> "char *") for storage, putting an element is done with placement new,
> getting an element is done with reinterpret_cast'ing the storage, like this:
>
> #include <new>
>
> struct Something {
> ?int value;
>
> ?Something() { value = 42; }
> };
>
> template <typename OBJECT, int MAX_SIZE>
> struct Container {
> ?union {
> ? ?char data[sizeof(OBJECT)*MAX_SIZE];
> ? ?// here goes a member which ensures proper alignment
> ?};
> ?int currentSize;
>
> ?Container() { currentSize=0; }
>
> ?void add() {
> ? ?new(data+sizeof(OBJECT)*currentSize) OBJECT;
> ? ?currentSize++;
> ?}
>
> ?OBJECT &operator[](int index) {
> ? ?// assert(index<currentSize);
> ? ?return reinterpret_cast<OBJECT*>(data)[index]; // gcc warns here
> ?}
> };
>
> void bar() {
> ?Container<Something, 5> c;
> ?c.add();
> ?c[0].value = 41;
> }
>
> Here, gcc warns on the reinterpret_cast line. ?However, as I understand,
> this usage cannot cause any harm. ?If I always access "data" as "OBJECT",
> nothing can go wrong, right? ?Even, if I access "data" as char sometimes,
> gcc should handle this case, I think. ?Of course, if "data" would be a
> non-char array, the situation would be different. ?Is the warning
> appropriate here? ?Can a cast from char[] cause anything bad? If it's
> difficult to detect this usage method on the compiler side, is there any way
> to avoid this warning just for this line (maybe rephrasing this line somehow
> to tell gcc that everything is OK)?

The code looks ok and should work fine with GCC 4.5 and newer.  No
guarantees for older versions though, if it works there it certainly isn't
by design.

Richard.

> Thanks,
> Geza
>


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]