通过对数组元素的引用替换变量

Replace a variable, by a reference to an element of an array

我有一个 class 可以正常工作并使用整数作为标志变量(按位运算):

class foo{
   uint32_t flags;
   ...
};

我想将此标志扩展到更大的大小,例如 512。但我想让旧代码的工作与新大小无关。

我试过了,但没有用:

class foo{
   uint32_t flags_ext[16];
   uint32_t& flags = flags_ext[0];
   ...
};

在做赋值等时给我一堆问题。另外警告我可能会双重删除内存。

有什么方法可以使代码正常运行但 uint32_t 成为数组的一部分?

实施适当的默认值、复制构造函数和赋值运算符,您应该可以开始了:

class foo{
   uint32_t flags_ext[16];
   uint32_t& flags;

   foo():
       flags( flags_ext[0] )
   {}

   // copy c'tor takes care _not_ to copy the reference member
   foo( const foo& other ):
       flags( flags_ext[0] )
   { ::memcpy(flags_ext, other.flags_ext, sizeof(flags_ext)); }

   const foo& operator=(const foo& other) {
      if( this==&other )
          return *this;
      // do _not_ copy the 'flags' member!
      ::memcpy(flags_ext, other.flags_ext, sizeof(flags_ext));
      return *this;
   }
};