现在的位置: 首页 > 综合 > 正文

[初]对于C++内存模型的一个测试小程序

2013年08月25日 ⁄ 综合 ⁄ 共 969字 ⁄ 字号 评论关闭

#include <iostream>
#include <cstdio>

using namespace std;

//对于C++内存模型的一个测试小程序
//author:snail
//date:2007-03-02

//*

class MemoryKiller{
public:
    MemoryKiller(){};
private:
    int bigMemory[1024*1024]; 
};

//全局区(静态区)(static):全局变量和静态变量的存储是放在一块的
//下面这行需要800的内存,而且没有出错,说明gcc编译器应该没有对静态区
//做大小限制~~任意大小:)
int Global_Memory_killer[200000000];

int main(){
    // 在这里,我又向系统要了800M内存!
    int* p = new int[200000000];
   
    //堆区(heap):gcc编译器对堆区的大小也没有做任何限制。
    MemoryKiller *mk = new MemoryKiller();
    cout << "create MemoryKiller on the heap successful!" << endl;

    //MemoryKiller k是这样建立在栈上还是建立在堆上?
    //这个问题困扰了我好久,结果程序跑起来,结果马上就出现了(挂了。。)
    //最终还是验证对象是建立在堆栈上的~~~
    //MemoryKiller k;
   
    cout << "create MemoryKiller on the stack successful!" << endl;
   
    //在这里我又向系统要800内存,不过这次可能就没这么幸运了!
    //这时候系统对我说这么多了,不过系统有2种表达方式,一种
    //丢出异常,另一种丢个0给我,因为我在申请空间的时候明确
    //告诉系统不要丢异常,就是(nothrow)这个东西,明确说明我要0.
    //所以系统返回个0给我,真听话啊!
    if(int *q = new(nothrow) int[200000000]){
        cout << "success!";
    }else{
        cout << "lost!";
    }  
   
    system("pause");
}

//*/
 
 

抱歉!评论已关闭.