3

我有一些使用类型双关语的代码,以避免调用成员“对象”的构造函数和析构函数,除非/直到实际上有必要使用该对象。

它工作正常,但在 g++ 4.4.3 下,我收到了这个可怕的编译器警告:

jaf@jeremy-desktop:~$ g++ -O3 -Wall puns.cpp 
puns.cpp: In instantiation of ‘Lightweight<Heavyweight>’:
puns.cpp:68:   instantiated from here 
puns.cpp:12: warning: ignoring attributes applied to ‘Heavyweight’ after definition
puns.cpp: In destructor ‘Lightweight<T>::~Lightweight() [with T = Heavyweight]’:
puns.cpp:68:   instantiated from here
puns.cpp:20: warning: dereferencing type-punned pointer will break strict-aliasing rules
puns.cpp: In member function ‘void Lightweight<T>::MethodThatGetsCalledRarely() [with T = Heavyweight]’:
puns.cpp:70:   instantiated from here
puns.cpp:36: warning: dereferencing type-punned pointer will break strict-aliasing rules

我的代码尝试使用 gcc 的 __attribute((__may_alias__)) 让 gcc 知道潜在的别名,但 gcc 似乎不明白我想告诉它什么。我做错了什么,还是 gcc 4.4.3 的 __may_alias__ 属性有一些问题?

重现编译器警告的玩具代码如下:

#include <stdio.h>
#include <memory>    // for placement new
#include <stdlib.h>  // for rand()

/** Templated class that I want to be quick to construct and destroy.
  * In particular, I don't want to have T's constructor called unless
  * I actually need it, and I also don't want to use dynamic allocation.
  **/
template<class T> 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) (reinterpret_cast<T_may_alias *>(_optionalObject._buf))->~T_may_alias();
   }

   void MethodThatGetsCalledOften()
   {
      // Imagine some useful code here
   }

   void MethodThatGetsCalledRarely()
   {
      if (_isObjectConstructed == false)
      {
         // demand-construct the heavy object, since we actually need to use it now
         (void) new (reinterpret_cast<T_may_alias *>(_optionalObject._buf)) T();
         _isObjectConstructed = true;
      }
      (reinterpret_cast<T_may_alias *>(_optionalObject._buf))->DoSomething();
   }

private:
   union {
      char _buf[sizeof(T)];
      unsigned long long _thisIsOnlyHereToForceEightByteAlignment;
   } _optionalObject;

   bool _isObjectConstructed;
};

static int _iterationCounter = 0;
static int _heavyCounter     = 0;

/** Example of a class that takes (relatively) a lot of resources to construct or destroy. */
class Heavyweight
{
public:
   Heavyweight()
   {
      printf("Heavyweight constructor, this is an expensive call!\n");
      _heavyCounter++;
   }

   void DoSomething() {/* Imagine some useful code here*/}
};

static void SomeMethod()
{
   _iterationCounter++;

   Lightweight<Heavyweight> obj;
   if ((rand()%1000) != 0) obj.MethodThatGetsCalledOften();
                      else obj.MethodThatGetsCalledRarely();
}

int main(int argc, char ** argv)
{
   for (int i=0; i<1000; i++) SomeMethod();
   printf("Heavyweight ctor was executed only %i times out of %i iterations, we avoid %.1f%% of the ctor calls!.\n", _heavyCounter, _iterationCounter, 100.0f*(1.0f-(((float)_heavyCounter)/((float)_iterationCounter))));
   return 0;
}
4

3 回答 3

5

我认为typedefGCC 令人困惑。当直接应用于变量定义时,这些类型的属性似乎效果最好。

这个版本的课程适合我(GCC 4.6.0):

template<class T> 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<T *>(_optionalObject._buf));
      p->~T();
    }
  }

  void MethodThatGetsCalledOften()
  {
    // Imagine some useful code here
  }

  void MethodThatGetsCalledRarely()
  {
    T * __attribute__((__may_alias__)) p
      = (reinterpret_cast<T *>(_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.]
于 2011-06-11T00:01:08.360 回答
2

我会主张让你的包含类只包含一个足够大小的 char 数组来包含你的成员“对象”,然后使用placement new 在 char 数组之上进行初始化。这具有符合规范和交叉编译器的好处。唯一的问题是您必须知道成员对象的字符大小,这可能会给您带来麻烦。

是否有理由不能让成员成为指针并使用 new 和 delete?

于 2011-07-14T22:17:37.217 回答
2

如果_isObjectConstructed用指向对象的指针替换会怎样:

轻量级
{
上市:
   Lightweight() : object(NULL) {/* 空 */}

   〜轻量级()
   {
      // 调用对象的析构函数,前提是我们曾经构造过它
      if (object) object->~T();
   }

   无效 MethodThatGetsCalledOften()
   {
      // 在这里想象一些有用的代码
   }

   void MethodThatGetsCalledRarely()
   {
      如果(!对象)
      {
         // 按需构造重对象,因为我们现在实际上需要使用它
         object = new (_optionalObject._buf) T();
      }
      对象->DoSomething();
   }

私人的:
   联合{
      char _buf[sizeof(T)];
      unsigned long long _thisIsOnlyHereToForceEightByteAlignment;
   } _可选对象;

   T *对象;
};

注意,没有 GCC 扩展,只有纯 C++ 代码。

使用 aT*而不是 abool甚至不会变得Lightweight更大!

于 2011-12-13T15:33:17.200 回答