看了书上,new的定位功能可以在你指定的地址开辟新的内存。但是貌似不用这个新功能照样也可以做到这些。
比如
int *pa=new int;
double *pa_a = (double *) pa;
这个也可以生成一个指向 pa 地址的另一个类型的指针。其地址应该也没发生变化吧?
希望有大神能解决我的疑惑。我实在是感觉new的定位功能貌似很鸡肋一样。我通过强制转换指针类型也可以做到这个需求。
以上为知乎https://www.zhihu.com/question/38230267的内容,我也感到奇怪,在工程中会用到么?
The example you gave is for basic types, and it’s not done well. The
The function ofint
ofsize
is smaller than thedouble
ofsize
, so it’s easy to cause problemsplacement new
is not to open new memory, but to construct an object on the specified memory blockFor example:
In the above code,
pb
does not point to a newly allocated memory, but reuses the memory pointed to bypa
.directly calls the structure of
pa
on the memory pointed to byB
After the function,is executed,
pb == pa
, just theA
object in the memory becomes theB
objectNote:
sizeof(B) <= sizeof(A)
As for the
强制类型转换
you mentioned, only the pointer type has been changed, and the constructor ofB
cannot be called. That is, the memory block is still aA
object but not aB
objectIn 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
内存池
). toplacement new
(reusing the original memory block can avoid the frequent occurrence ofmalloc
andfree
)For example, if you use
stl
every day, thememory allocator
underneath it is usedplacement new
(for details, you can read《stl源码剖析》
)