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

后端 未结 3 1828
被撕碎了的回忆
被撕碎了的回忆 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 18:16

    What if you replace _isObjectConstructed with a pointer to the object:

    class Lightweight
    {
    public:
       Lightweight() : object(NULL) {/* empty */}
    
       ~Lightweight()
       {
          // call object's destructor, only if we ever constructed it
          if (object) object->~T();
       }
    
       void MethodThatGetsCalledOften()
       {
          // Imagine some useful code here
       }
    
       void MethodThatGetsCalledRarely()
       {
          if (!object)
          {
             // demand-construct the heavy object, since we actually need to use it now
             object = new (_optionalObject._buf) T();
          }
          object->DoSomething();
       }
    
    private:
       union {
          char _buf[sizeof(T)];
          unsigned long long _thisIsOnlyHereToForceEightByteAlignment;
       } _optionalObject;
    
       T *object;
    };
    

    Note, no GCC extension, only pure C++ code.

    Using a T* instead of a bool won't even make Lightweight any bigger!

提交回复
热议问题