0

演算子 new と delete を malloc と free に置き換えようとしています (その理由があります)。問題は次のコードに示されています。

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("%s\n", 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("%s\n", 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("%d\n", pmyclass[i].get_number());
        pmyclass[i].myclass::~myclass();
    }

    free(pmyclass);

    return 0;
}
4

3 に答える 3