c++ - 用魔数(Magic Number)初始化一 block 内存的简洁方法

标签 c++ initialization

我所指的几个例子:

typedef struct SOME_STRUCT {
  unsigned int x1;
  unsigned int x2;
  unsigned int x3;
  unsigned int x4;

  // What I expected would work, but doesn't; the 2nd parameter gets
  // turned into an 8-bit quantity at some point within memset
  SOME_STRUCT() { memset( this, 0xFEEDFACE, sizeof( *this ) ); }

  // Something that worked, but seems hokey/hackish
  SOME_STRUCT() {
    unsigned int *me = (unsigned int *)this;
    for( int ii = 0; ii < sizeof(*this)/sizeof(*me); ++ii ) {
      me[ii] = 0xFEEDFACE;
    }
  }

  // The far-more-verbose-but-C++-way-of-doing-it
  // This works, but doesn't lend itself very well
  // to being a drop-in way to pull this off on
  // any struct.
  SOME_STRUCT() :  x1( 0xFEEDFACE )
                 , x2( 0XFEEDFACE )
                 , x3( 0XFEEDFACE )
                 , x4( 0XFEEDFACE ) {}

  // This would work, but I figured there would be a standard
  // function that would alleviate the need to do it myself
  SOME_STRUCT() { my_memset( this, 0xFEEDFACE, sizeof(*this) ); }
}

我不能在这里使用 valgrind,而且就我可以访问的各种调试库而言,我的选择是有限的——这就是为什么我要自己为这个一次性案例做这件事。

最佳答案

这是安全使用 std::generate() 的部分示例:

#include <algorithm>

struct Wizard {
    size_t i;
    static unsigned char magic[4];
    Wizard() : i(0) {}
    unsigned char operator()() {
        size_t j = i++;
        i %= sizeof(magic); // Not strictly necessary due to wrapping.
        return magic[j];
    }
};

unsigned char Wizard::magic[4] = {0xDE,0xAD,0xBE,0xEF};

std::generate(reinterpret_cast<unsigned char*>(this),
              reinterpret_cast<unsigned char*>(this) + sizeof(*this),
              Wizard());

(当然,字节序可能正确也可能不正确,这取决于您的外观以及您期望在执行时看到的内容!)

关于c++ - 用魔数(Magic Number)初始化一 block 内存的简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7575708/

相关文章:

c++ - 光线追踪器反射有颗粒感

c++ - 应用程序中有很多线程会适得其反吗?

c++11 - 我应该怎么做才能将数据/值/对象添加到初始化列表,然后将其发送到构造函数?

ios - Swift - 初始化 fatal error

c++ - 在 C++ 中使用 dlsym 加载共享对象函数

c++ - 函数使用对象,对象使用函数

c++ - 在 static_cast 之后执行类型安全检查的任何方法?

java - 使用 rawtype 数组初始化的通配符集合数组

c++ - 类成员,隐式初始化为零?

结构 vector 的 C++ 初始化