我正在探索在C++中实现真(部分)不可变数据结构的可能性.由于C++似乎没有区分变量和变量存储的对象,因此真正替换对象(没有赋值操作!)的唯一方法是使用placement new:
auto var = Immutable(state0);
// the following is illegal as it requires assignment to
// an immutable object
var = Immutable(state1);
// however, the following would work as it constructs a new object
// in place of the old one
new (&var) Immutable(state1);
Run Code Online (Sandbox Code Playgroud)
假设没有非平凡的析构函数可以运行,这在C++中是合法的还是我应该期望未定义的行为?如果它依赖于标准,那么我可以期待这个最小/最大标准版本能够工作吗?
简介:这个问题是我收集的C和C++(以及C/C++常见子集)问题的一部分,这些问题涉及允许具有严格相同的字节表示的指针对象具有不同的"值",即行为不同对于某些操作(包括在一个对象上定义了行为,在另一个对象上定义了未定义的行为).
在另一个引起很多混淆的问题之后,这里有关于指针语义的问题,希望能够解决问题:
这个程序在所有情况下都有效吗?唯一有趣的部分是在"pa1 == pb"分支中.
#include <stdio.h>
#include <string.h>
int main() {
int a[1] = { 0 }, *pa1 = &a[0] + 1, b = 1, *pb = &b;
if (memcmp (&pa1, &pb, sizeof pa1) == 0) {
int *p;
printf ("pa1 == pb\n"); // interesting part
memcpy (&p, &pa1, sizeof p); // make a copy of the representation
memcpy (&pa1, &p, sizeof p); // pa1 is a copy of the bytes of …Run Code Online (Sandbox Code Playgroud)