// 以下,在C中合法,在C++中未定义(因为没有经过 placement new) void *p = malloc(sizeof(float)); float f = 1.0f; memcpy( p, &f, sizeof(float)); // Effective type of *p is float in C // Or float *fp = p; fp = 1.0f; // Effective type of *p is float in C
以及 C++ 认为类型应该初始化后才能被使用
1
float *fp = new (p) float{1.0f} ; // Dynamic type of *p is now float
来点反例
1
1 2 3 4 5 6 7 8 9 10 11 12 13 14
intfoo( float *f, int *i ){ *i = 1; *f = 0.f;
return *i; }
intmain(){ int x = 0;
std::cout << x << "\n"; // Expect 0,Output 0 x = foo((float*)(&x), &x); std::cout << x << "\n"; // Expect 0, But Output 1 }
// 假设 len 是 sizeof(double) 的整数倍 doublebar(unsignedchar *p, size_t len){ double result = 0.0;
for (size_t index = 0; index < len; index += sizeof(double)) { double ui; memcpy(&ui, &p[index], sizeof(double)); // right // double ui = *(double*)(&p[index]); -> ub result += foo(ui); }
return result; }
__restrict__
这个关键字会提示编译期这两个指针即使是相似的, 也不会指向同一片内存
1 2 3 4 5 6
intadd(int* __restrict__ a, int* __restrict__ b) { *a = 10; *b = 12; return *a + *b; }