#C++PrimerPlus# Chapter12_Exersice9_placenew2

上题中,使用定位new分配内存中存在两个问题。

1,pc3创建的时候覆盖掉了pc1,这是因为new对象时提供的地址(buffer)相同,应当给后创建的对象提供的地址一个偏移量sizeof(JustTesting);

2,delete [] buffer 未能调用定位new的两个对象pc1,pc3的析构函数,需要显式的调用他们。

程序清单如下:


// placenew2.cpp
#include <iostream>
#include <string>
#include <new>

using namespace std;

const int BUF = 512;

class JustTesting
{
private:
    string words;
    int number;
public:
    JustTesting(const string& s = "Just Testing", int n = 0)
    {
        words = s;
        number = n;
        cout << words << " constructed\n";
    }
    ~JustTesting() { cout << words << " destroyed\n"; }
    void Show() { cout << words << ", " << number << endl; }
};

int main()
{
    char* buffer = new char[BUF];

    JustTesting* pc1;
    JustTesting* pc2;
    pc1 = new (buffer) JustTesting;
    pc2 = new JustTesting("Heap1", 20);

    cout << "Memory block addresses:\n" << "buffer: " << (void*) buffer << "    heap: " << pc2 << endl;
    cout << "Memory contents:\n";
    cout << pc1 << ": ";
    pc1->Show();
    cout << pc2 << ": ";
    pc2->Show();

    JustTesting* pc3;
    JustTesting* pc4;
    pc3 = new (buffer + sizeof(JustTesting)) JustTesting("Better Idea", 6);
    pc4 = new JustTesting("Heap2", 10);

    cout << "Memory contents:\n";
    cout << pc3 << ": ";
    pc1->Show();
    cout << pc4 << ": ";
    pc2->Show();

    delete pc2;
    delete pc4;
    pc1->~JustTesting();
    pc3->~JustTesting();
    delete [] buffer;

    cout << "Done\n";

    system("pause>nul");
    return 0;
}


结束。

 

原文链接: https://www.cnblogs.com/zhuangdong/archive/2013/05/15/3079669.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    #C++PrimerPlus# Chapter12_Exersice9_placenew2

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/88598

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午11:43
下一篇 2023年2月9日 下午11:43

相关推荐