如何让new失败啊?
最近看书说,new失败后,会抛出异常,想尝试一下,但是如何让new失败呢?
我试过两种方法:
1是分配很大的数组,但是VS2010是在太智能了,数组长度太大时直接就在编译时报错:error C2148: 数组的总大小不得超过 0x7fffffff 字节。
2.是通过单例模式。我是现找的:
class CSingleton
{
//其他成员
public:
static CSingleton* GetInstance()
{
if ( m_pInstance == NULL ) //判断是否第一次调用
m_pInstance = new CSingleton();
return m_pInstance;
}
void fun()
{
cout<<"fun"<<endl;
}
private:
CSingleton(){};
static CSingleton *m_pInstance;
};
CSingleton* CSingleton::m_pInstance = NULL;
class Test2
{
public:
double dval;
};
int main()
{
CSingleton* p1 = CSingleton::GetInstance();
p1->fun();
CSingleton* p1arr = new CSingleton[2];
return 0;
}
#include<iostream>
using namespace std;
void* operator new(std::size_t) throw (std::bad_alloc){
throw bad_alloc();
}
void operator delete(void* p) throw() {
}
int main() {
try {
char *p=new char(100);
}
catch(...) {
cout << "throw "<< endl;
}
}
int main()
{
try
{
for(int i=0;i<100;++i)
{
char *p=new char[0x7fffffff];
}
}
catch(...)
{
cout <<"something catched" <<endl;
}
return 0;
}