3 回答

TA貢獻1824條經驗 獲得超8個贊
new是運算符啊,在標準C++中,是不會返回NULL的,如果內存分配失敗的話,會拋出系統異常的。雖然CRT中的new可以返回Null,那也是在內存不足的時候?!?br/>Beginning in Visual C++ .NET 2002, the CRT's new function (in libc.lib, libcd.lib, libcmt.lib, libcmtd.lib, msvcrt.lib, and msvcrtd.lib) will continue to return NULL if memory allocation fails. However, the new function in the Standard C++ Library (in libcp.lib, libcpd.lib, libcpmt.lib, libcpmtd.lib, msvcprt.lib, and msvcprtd.lib) will support the behavior specified in the C++ standard, which is to throw a std::bad_alloc exception if the memory allocation fails.[1]

TA貢獻1821條經驗 獲得超5個贊
在類當中重載new運算符可以實現,如
bool nonew;
class A{
public:
A(int t):a(t){
}
int a;
void* operator new(unsigned int s){
if(nonew)return NULL;
else return malloc(s);
}
};
這樣一來nonew就成為了new A(...)是否返回NULL的開關

TA貢獻1820條經驗 獲得超9個贊
class A
{
public:
A* create()
{
if (...)
{
m_a = new A();
return m_a;
}
else
{
return null;
}
}
private:
A(){}
A* m_a;
}
把構造作為私有,然后自己寫個create之類的成員函數應該就可以滿足你的要求了吧。
- 3 回答
- 0 關注
- 364 瀏覽
添加回答
舉報