Strict aliasing plus placement new / explicit destructor call

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I'm trying to enable -fstrict-aliasing when building Firefox.  One
class in particular is proving difficult to make work properly.  We
use this class for lazily allocating objects on the stack.

Code is included at the end of this e-mail.  When I compile with -O2
-Wall, I get

   main.cpp:20: warning: dereferencing pointer ‘this.0’ does break
strict-aliasing rules

It seems that this warning is due to the cast in ~Lazy().  Note that I
can't rewrite Lazy<T>'s storage as a union because T may have a
constructor -- the whole purpose of the Lazy class is to let me
stack-allocate T without immediately calling its constructor.

Also, changing

      T* obj = reinterpret_cast<T*>(bytes);

to

      T* __attribute__((may_alias)) obj = reinterpret_cast<T*>(bytes);

doesn't eliminate the warning.

I'm out of ideas.  Is there a way to accomplish what I'm trying to do
here without disabling strict aliasing?  I'd hate to give up now.

Thanks for your help,
-Justin



template <class T>
class Lazy
{
  public:
    char bytes[sizeof(T)];

    void construct() {
      new(bytes) T();
    }

    ~Lazy() {
      T* obj = reinterpret_cast<T*>(bytes);
      obj->~T();
    }
};

class FooBase {
  public:
    ~FooBase() {
      *n = 0;  // line 20 (where the error is)
    }

    int *n;
};

class Foo : public FooBase {
  public:
    int num;
};

int main()
{
  Lazy<Foo> foo;
  return 0;
}



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux