c++ - C++ 中的共享内存缓冲区不违反严格的别名规则

标签 c++ memory buffer strict-aliasing type-punning

我正在努力在不违反 C99 严格别名规则的情况下实现共享内存缓冲区。

假设我有一些代码处理一些数据并且需要有一些“暂存”内存来运行。我可以这样写:

void foo(... some arguments here ...) {
  int* scratchMem = new int[1000];   // Allocate.
  // Do stuff...
  delete[] scratchMem;  // Free.
}

然后我有另一个函数可以做一些其他的事情,也需要一个临时缓冲区:

void bar(...arguments...) {
  float* scratchMem = new float[1000];   // Allocate.
  // Do other stuff...
  delete[] scratchMem;  // Free.
}

问题是 foo() 和 bar() 可能在操作期间被调用多次,并且在整个地方进行堆分配在性能和内存碎片方面可能非常糟糕。一个明显的解决方案是分配一个适当大小的公共(public)共享内存缓冲区一次,然后将其作为参数传递给 foo() 和 bar(),BYOB 风格:

void foo(void* scratchMem);
void bar(void* scratchMem);

int main() {
  const int iAmBigEnough = 5000;
  int* scratchMem = new int[iAmBigEnough];

  foo(scratchMem);
  bar(scratchMem);

  delete[] scratchMem;
  return 0;
}

void foo(void* scratchMem) {
  int* smem = (int*)scratchMem;
  // Dereferencing smem will break strict-aliasing rules!
  // ...
}

void bar(void* scratchMem) {
  float* smem = (float*)scratchMem;
  // Dereferencing smem will break strict-aliasing rules!
  // ...
}


我想我现在有两个问题:
- 如何实现不违反别名规则的共享公共(public)暂存内存缓冲区?
- 尽管上面的代码确实违反了严格的别名规则,但别名不会造成“伤害”。因此,任何理智的编译器都可以生成(优化的)代码,但仍然让我陷入困境吗?

谢谢

最佳答案

实际上,您所写的并不是严格的别名违规。

C++11 规范 3.10.10 说:

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined

所以导致未定义行为的是访问存储的值,而不仅仅是创建指向它的指针。您的示例没有违反任何内容。它需要做下一步:float badValue = smem[0]。 smem[0] 从共享缓冲区中获取存储的值,造成别名冲突。

当然,您不会在设置之前只获取 smem[0]。你要先写信给它。分配给相同的内存不会访问存储的值,因此没有混叠但是,在对象还活着的时候覆盖它的顶部是非法的。为了证明我们是安全的,我们需要 3.8.4 的对象生命周期:

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; ... [continues on regarding consequences of not calling destructors]

你有一个 POD 类型,如此简单的析构函数,所以你可以简单地口头声明“int 对象都在它们生命周期的尽头,我正在使用 floats 的空间。”然后您将空间重新用于 float ,并且不会发生别名冲突。

关于c++ - C++ 中的共享内存缓冲区不违反严格的别名规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18624449/

相关文章:

c++ - 如何让编译器推断出 C++11 中模板化方法的返回类型?

c++ - 编译外部库时涉及增量 (C1073) 编译的错误

c++ - (C++内存编辑)将 "THREADSTACK0"转换为地址

memory - Go: time.sleep 和内存使用

c - 双向链表中的插入和删除

java - Android:对 findViewById 的引用

c++ - UCHAR 或 WCHAR 用于通信缓冲区

ruby - 使用 progressbar/ruby-progressbar gem 时出现 Zlib::BufError

iphone - 调整 AudioUnit 缓冲区的长度

c++ - 在结构 vector 的结构 vector 的映射中存储数据