3 回答

TA贡献1824条经验 获得超8个赞
new是运算符啊,在标准C++中,是不会返回NULL的,如果内存分配失败的话,会抛出系统异常的。虽然CRT中的new可以返回Null,那也是在内存不足的时候。
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 关注
- 380 浏览
添加回答
举报