On Tue, Jun 7, 2011 at 2:58 PM, Herman, Geza <g...@bitquad.com> wrote: > On 06/07/2011 12:27 PM, Richard Guenther wrote: >> >> On Tue, Jun 7, 2011 at 5:51 AM, Herman, Geza<g...@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. > > Thanks for the answer! > > You're right, this example compiles without warnings with GCC 4.5. My > mistake, I copied a version which warns only with GCC 4.4 in my previous > email. But, if I add another member function, like: > > OBJECT &first() { > return reinterpret_cast<OBJECT*>(data)[0]; // gcc warns here > } > > and call it from "bar()": > > c.first().value = 41; > > I tried both GCC 4.5, and the latest available in my system (gcc version > 4.7.0 20110531 (experimental) [trunk revision 174470]), both produces a > warning. Is it a false positive warning?
Yes. Richard. > Luckily, generated code works, even with previous versions of GCC. > >> >> Richard. >> >>> Thanks, >>> Geza >>> > >