我想了解operator new(std::size_t)和new-expression之间的所有区别。
#include <iostream>
#include <new>
using std::cout;
struct A
{
int a;
char b;
A(){ cout << "A\n"; a = 5; b = 'a'; }
~A(){ cout << "~A\n"; }
};
A *a = (A*)operator new(sizeof(A)); //allocates 8 bytes and return void*
A *b = new A(); //allocates 8 bytes, invoke a default constructor and return A*你能提供他们之间的所有差异吗?他们的工作方式不同吗?
发布于 2014-07-12 12:47:12
new表达式调用分配函数operator new。分配函数获得内存,new表达式将内存转换为对象(通过构造它们)。
因此,下面的代码:
T * p = new T(1, true, 'x');
delete p;相当于以下操作序列:
void * addr = operator new(sizeof(T)); // allocation
T * p = new (addr) T(1, true, 'x'); // construction
p->~T(); // destruction
operator delete(addr); // deallocation请注意,您总是需要一个new表达式来创建对象(即调用构造函数)-构造函数没有名称,不能直接调用。在这种情况下,我们使用默认的布局-新表达式,它只做创建对象,不像非布局形式,它同时执行内存分配和对象构造。
发布于 2014-07-12 12:52:04
new-expression为新分配的对象分配所需的内存,和调用相应的构造函数(给定参数)。
new(std::size_t) operator只分配内存。
在http://www.cplusplus.com/reference/new/operator%20new/阅读更多内容
https://stackoverflow.com/questions/24713022
复制相似问题