使用
我知道我可以使用放置
我想要实现的与下面的示例相同,但使用
malloc
和 free
,可以轻松地分配带有额外数据的结构。但是如何使用 new
/ delete
实现相同的功能呢?我知道我可以使用放置
new
语法和 malloc
进行分配,但如果我将一个对象放置在由 malloc
分配的内存中,delete
是否能正常并可移植地工作呢?我想要实现的与下面的示例相同,但使用
new
/ delete
而不是 malloc
/ free
,以便正确调用构造函数 / 析构函数:#include <cstdlib>
#include <cstring>
#include <iostream>
class Hamburger {
int tastyness;
public:
char *GetMeat();
};
char *Hamburger::GetMeat() {
return reinterpret_cast<char *>(this) + sizeof(Hamburger);
}
int main(int argc, char* argv[])
{
Hamburger* hb;
// Allocate a Hamburger with 4 extra bytes to store a string.
hb = reinterpret_cast<Hamburger*>(malloc(sizeof(Hamburger) + 4));
strcpy(hb->GetMeat(), "yum");
std::cout << "hamburger is " << hb->GetMeat() << std::endl;
free(hb);
}
输出:汉堡很好吃
int tastyness
通常被称为size_t size
,以便明显地展示其有多么有用。 - porgarmingduod