#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;
}


结束。

 

posted @ 2013-05-15 13:22  庄懂  阅读(138)  评论(0编辑  收藏  举报