Home  >  Q&A  >  body text

c++ - 【转自知乎】关于new的定位功能(placement new),这个功能是不是多余的?

看了书上,new的定位功能可以在你指定的地址开辟新的内存。但是貌似不用这个新功能照样也可以做到这些。
比如

int *pa=new int;
double *pa_a = (double *) pa;

这个也可以生成一个指向 pa 地址的另一个类型的指针。其地址应该也没发生变化吧?
希望有大神能解决我的疑惑。我实在是感觉new的定位功能貌似很鸡肋一样。我通过强制转换指针类型也可以做到这个需求。

以上为知乎https://www.zhihu.com/question/38230267的内容,我也感到奇怪,在工程中会用到么?

伊谢尔伦伊谢尔伦2765 days ago650

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-17 15:24:05

    The example you gave is for basic types, and it’s not done well. The int of size is smaller than the double of size, so it’s easy to cause problems

    The function of

    placement new is not to open new memory, but to construct an object on the specified memory block

    For example:

    struct A {...};
    struct B {...};
    
    A* pa = new A;
    pa->~A();
    B* pb = new (pa) B

    In the above code, pb does not point to a newly allocated memory, but reuses the memory pointed to by pa.
    directly calls the structure of pa on the memory pointed to by B After the function,
    is executed, pb == pa, just the A object in the memory becomes the B object
    Note: sizeof(B) <= sizeof(A)

    As for the 强制类型转换 you mentioned, only the pointer type has been changed, and the constructor of B cannot be called. That is, the memory block is still a A object but not a B object

    In engineering practice, it is generally used in memory management.
    is used in some situations where a more efficient and flexible memory allocation strategy is required (such as implementing your own 内存池). to placement new (reusing the original memory block can avoid the frequent occurrence of malloc and free)

    For example, if you use stl every day, the memory allocator underneath it is used placement new (for details, you can read 《stl源码剖析》)

    reply
    0
  • Cancelreply