将运算符 new 替换为 malloc

replace operator new with malloc

本文关键字:malloc 替换 new 运算符      更新时间:2023-10-16

我正在尝试用malloc和free替换运算符new并删除(我有理由)。问题显示在下面的代码中:

std::string *temp = (std::string *)malloc(sizeof(std::string) * 2); // allocate space for two string objects.
temp[0] = "hello!";
temp[1] = "world!";
for(int i = 0; i < 2; i++)
{
    printf("%sn", temp[i].c_str());
}
free(temp);
return 0; // causes SIGSEGV.

然而。。

std::string *temp = new std::string[2];
temp[0] = "hello!";
temp[1] = "world!";
for(int i = 0; i < 2; i++)
{
    printf("%sn", temp[i].c_str());
}
delete [] temp;
return 0; // works fine

为什么? 谁能建议我用malloc和free替换这些运算符的正确方法是什么?

问候。

编辑:这只是一个例子,我没有使用标准的C++库。

编辑:这样的事情呢?

class myclass
{
    public:
        myclass()
        {
            this->number = 0;
        }
        myclass(const myclass &other)
        {
            this->number = other.get_number();
        }
        ~myclass()
        {
            this->number = 0;
        }
        int get_number() const
        {
            return this->number;
        }
        void set_number(int num)
        {
            this->number = num;
        }
    private:
        int number;
};
int main(int argc, char *argv[])
{
    myclass m1, m2;
    m1.set_number(5);
    m2.set_number(3);
    myclass *pmyclass = (myclass *)malloc(sizeof(myclass) * 2);
    pmyclass[0] = myclass(m1);
    pmyclass[1] = myclass(m2);
    for(int i = 0; i < 2; i++)
    {
        printf("%dn", pmyclass[i].get_number());
        pmyclass[i].myclass::~myclass();
    }
    free(pmyclass);
    return 0;
}

mallocfree不调用C++类的构造函数和析构函数。它也不会存储有关数组中分配的元素数量的信息(就像您正在做的那样)。这意味着内存只是分配,但永远不会初始化。但是,您仍然可以手动构造和销毁对象。

您应该首先使用 placement-new 构造对象。这要求您将 a 指针传递给要创建对象的位置,并指定需要实例化的对象类型。例如,将字符串文本分配给已分配(但未初始化)字符串对象的第一行如下所示:

new(&temp[0]) std::string("hello!");

完成字符串后,您需要通过直接调用它们的析构函数来销毁它们。

temp[0].std::string::~string();

您提出的代码如下所示:

// allocate space for two string objects.
std::string *temp = (std::string *)malloc(sizeof(std::string) * 2); 
// Using placement-new to constructo the strings
new(&temp[0]) std::string("hello!");
new(&temp[1]) std::string("world!");
for (int i = 0; i < 2; i++)
{
    printf("%sn", temp[i].c_str());
}
//  Destroy the strings by directly calling the destructor
temp[0].std::string::~string();
temp[1].std::string::~string();
free(temp);

如果你真的想掉进这个兔子洞......好吧,你需要放置新的,你需要手动调用析构函数。这是它的外观:

#include <string>
#include <stdlib.h>
#include <stdio.h>
int main()
{
    std::string *temp = (std::string *)malloc(sizeof(std::string) * 2); // allocate space for two string objects.
    new (&temp[0]) std::string("hello!");
    new (&temp[1]) std::string("world!");
    for(int i = 0; i < 2; i++)
    {
        printf("%sn", temp[i].c_str());
    }
    temp[1].std::string::~string();
    temp[0].std::string::~string();
    free(temp);
    return 0;
}

由于malloc为您提供了一个未初始化的内存块,因此您需要在适当的内存插槽中构造对象,并且在释放内存之前,您必须手动销毁它们。

你想用malloc实现自己的operator new(),而不是用malloc替换operator new

要实现operator new(),只需像编写任何其他函数一样编写它。

void* operator new() (size_t sz) { return malloc(sz); }

如果你想要一个在失败时抛出std::bad_alloc的标准兼容版本,只需插入你的代码。

operator delete留给读者作为练习,operator new[]()operator delete[]()也是如此。