0 c++ malloc inheritance new-operator
例如有一个链
class A
{
int a;
int b;
public:
A();
};
class B: public A
{
int c;
char b;
public:
B()
};
Run Code Online (Sandbox Code Playgroud)
以普通的方式创建派生类的对象我们可以使用这种形式
A* ptr = new B()
Run Code Online (Sandbox Code Playgroud)
如何使用 malloc 做同样的事情?
Malloc 返回一个void*指向原始分配内存的指针。只需在该内存上使用放置新运算符即可。
void* mem = malloc( sizeof(B) );
A* ptr = new(mem) B(); // builds object in location pointed by mem
Run Code Online (Sandbox Code Playgroud)
放置 new 不分配内存,它只是在给定的位置构造您的对象。