new定位运算符

定位new运算符:new负责在堆中找到一个足以满足要求的内存块,它让你能够指定要使用的位置。头文件#include<new>

#include<iostream>

#define MAX 50

using namespace std;

char buff[MAX];

class justTest
{
private:
    char *str;
    int num;
public:
    justTest(char *str1, int n)
    {
        str = str1;
        num = n;
        cout << str << " " << num << endl;
    }
    ~justTest()
    {
        cout << "destory of class:" << num << endl;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    justTest *pc1,*pc2;
    pc1 = new(buff)justTest("hello1", 1);
    pc2 = new justTest("hello2", 2);
    cout << "address of pc1:" << pc1 << endl;
    cout << "address of pc2:" << pc2 << endl;
    justTest *pc3, *pc4;
    pc4 = new(buff)justTest("hello4", 4);
    pc3 = new justTest("hello3", 3);
    cout << "address of pc3:" << pc3 << endl;
    cout << "address of pc4:" << pc4 << endl;
    //delete pc1;    //此语句错误
    delete pc2;

   delete []buff
    system("pause");
    return 0;
}

上述程序中,pc1与pc4就是new定位运算符的指针,该指针指向的类就是在buff这个内存中。上述运行结果为

hello1 1
hello2 2
address of pc1:00C80688
address of pc2:00B392D8
hello4 4
hello3 3
address of pc3:00B3CA10
address of pc4:00C80688
destory of class:2

由上可以看到pc1与pc4的值是一样的,因此new定位运算符定义的一个新对象将会覆盖用于第一个对象的内存单元。在delete []buff时不会调用pc1与pc4的析构函数。要调用只能显示的调用,即pc1->~justTest()。在定义pc4时,可以按照下面定义:

pc4 = new(buff+sizeof(justTest))justTest("hello4",4);

猜你喜欢

转载自blog.csdn.net/yihuanyihuan/article/details/84147629