10

C++ malloc出来的内存,可以手动调用构造函数吗?

 3 years ago
source link: https://www.zhihu.com/question/463874553/answer/1948307131
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
C++ malloc出来的内存,可以手动调用构造函数吗?
登录后你可以
不限量看优质回答私信答主深度交流精彩内容一键收藏
C++程序猿, 公众号:高级开发者

先分配(不管是堆上还是栈上)预留一块内存,然后按需构造对象,是一件很常见并很合理的事情。

无论是智能指针的引用计数控制块,还是optional的对象等等,都是先手动预留出来一块内存,然后手动按需调用对应的构造函数。

这其中涉及两个问题,预留的内存从哪来,可以来自于栈,可以从malloc获得,也可以通过new得到,又或者从静态空间得到;第二个问题是如何在已有内存上构造对象,需要通过placement new来构造。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK