gcc: How to use __attribute((__may_alias__)) properly to avoid “derefencing type-punned pointer” warning

后端 未结 3 1837
被撕碎了的回忆
被撕碎了的回忆 2021-02-06 17:41

I\'ve got some code that uses type-punning to avoid having to call a member \"object\"\'s constructor and destructor unless/until it\'s actually necessary to use the object.

3条回答
  •  死守一世寂寞
    2021-02-06 17:56

    I think the typedef is confusing GCC. These sorts of attributes seem to work best when applied directly to variable definitions.

    This version of your class works for me (GCC 4.6.0):

    template class Lightweight
    {
    private:
      //  typedef T __attribute((__may_alias__)) T_may_alias;
    
    public:
      Lightweight() : _isObjectConstructed(false) {/* empty */}
    
      ~Lightweight()
      {
        // call object's destructor, only if we ever constructed it
        if (_isObjectConstructed) {
          T * __attribute__((__may_alias__)) p
            = (reinterpret_cast(_optionalObject._buf));
          p->~T();
        }
      }
    
      void MethodThatGetsCalledOften()
      {
        // Imagine some useful code here
      }
    
      void MethodThatGetsCalledRarely()
      {
        T * __attribute__((__may_alias__)) p
          = (reinterpret_cast(_optionalObject._buf));
        if (_isObjectConstructed == false)
          {
            // demand-construct the heavy object, since we actually need to use it now
    
            (void) new (p) T();
            _isObjectConstructed = true;
          }
          p->DoSomething();
      }
    
      [etc.]
    

提交回复
热议问题