[C++] NEW Advanced Usage

NEW Advanced Usage

将分配的内存限定在特定的一块区域

#include<iostream>
#include<new>
const int buf(512);
int N(5);
char buffer[buf] = {0};

using namespace std;
void main()
{
    double *p1, *p2;

    std::cout << "\n\n\n";
    p1 = new double[N];
    p2 = new (buffer)double[N];
    for (int i = 0; i < N; i++)
    {
            p1[i] = p2[i] = i + 10.8;
            std::cout << "p1===   " << &p1[i] << "  " << p1[i];
            std::cout << "   p2===   " << &p2[i] << "  " << p2[i] << std::endl;
    }

    double *p3, *p4;
    std::cout << "\n\n\n";
    p3 = new double[N];
    p4 = new (buffer)double[N];
    
    for (int i = 0; i < N; i++)
    {
        p3[i] = p4[i] = i + 10.8 ;
        std::cout << "p3===   " << &p3[i] << "  " << p3[i];
        std::cout << "   p4===   " << &p4[i] << "  " << p4[i] << std::endl;
    }

    double *p5, *p6;
    std::cout << "\n\n\n";
    p5 = new double[N];
    p6 = new (buffer)double[N];

    for (int i = 0; i < N; i++)
    {
        p6[i] = p5[i] = i + 10.8;
        std::cout << "p5===   " << &p5[i] << "  " << p5[i];
        std::cout << "   p6===   " << &p6[i] << "  " << p6[i] << std::endl;
    }
    std::cin.get();
}

 

p2 p4 p6 的地址保持一样!!!

posted @ 2015-11-19 23:15  Jonas0608  阅读(235)  评论(0编辑  收藏  举报