#C++PrimerPlus# Chapter12_Exersice8_placenew1

试用使用定位new运算符给对象分配内存。

程序清单如下:


// placenew1.cpp
#include <iostream>
#include <string>
#include <new>    // 使用定位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() const { cout << words << ", " << number << endl;}
};


int main()
{
    char* buffer = new char[BUF];    // 创建内存缓冲区

    JustTesting* pc1;
    JustTesting* pc2;
    pc1 = new (buffer) JustTesting;    // 定位new运算符分配内存
    pc2 = new JustTesting("Heap1", 20);

    cout << "Memory block addresses:\n" << "buffer: " << (void*) buffer << "    heap: " << pc2 << endl;    // (void*)空类型指针
    cout << "Memory contents:\n";
    cout << pc1 << ": ";
    pc1->Show();
    cout << pc2 << ": ";
    pc2->Show();

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

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

    delete pc2;
    delete pc4;
    delete [] buffer;
    
    cout << "Done\n";

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


结束。

 

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