C++ placement new

前端 未结 5 811
我在风中等你
我在风中等你 2020-12-01 20:01

Sorry if this question will sound stupid, but I\'m just starting to learn C++ and there is something confusing me about the placement new

I\'ve been reading C++ Prim

5条回答
  •  隐瞒了意图╮
    2020-12-01 20:15

    Yes, the char array and the double array would overlap, more specifically they would start at the same address in memory, i.e. (long)buffer and (long)pd1 would be the same. We can emphasize the overlap even more by making the byte sizes match (assuming sizeof(char) == 1):

    const int N = 5;
    char buffer[N * sizeof(double)];
    double *pd1 = new (buffer) double[N];
    

    Yes, if you modify the data pd1 points to, then the data buffer points to would also be modified. And the other way round as well. (See also the GCC flag -fstrict-aliasing to learn about how compiler optimizations work with such an overlap.)

提交回复
热议问题