【发布时间】:2013-02-23 21:04:20
【问题描述】:
我有一个 C++ 程序,其中 new 运算符被重载。问题是
如果我在new 运算符中的分配失败,我仍在调用构造函数。
我知道我可以通过抛出 std::bad_alloc 来避免这种情况,但我不想这样做。
我如何在重载的new 运算符中失败并且仍然不调用我的构造函数?
本质上我想实现类似new (std::nothrow)。
这里有一个例子来说明我的意思。 请注意,我正在测试的系统
on 没有内存保护。所以访问NULL 没有任何作用
示例 1:重载 new 运算符
#include <stdio.h>
#include <stdlib.h>
#include <memory>
class Test {
public:
Test(void) {
printf("Test constructor\n");
}
void print(void) {
printf("this: %p\n", this);
}
void* operator new(size_t size, unsigned int extra) {
void* ptr = malloc(size + extra);
ptr = NULL; // For testing purposes
if (ptr == NULL) {
// ?
}
return ptr;
}
};
int main(void) {
Test* t = new (1) Test;
t->print();
printf("t: %p\n", t);
return 0;
}
这个的输出是:
$ ./a.out
Test constructor
this: 00000000
t: 00000000
显然,当new 失败时,构造函数被调用。
示例 2:带有 new (std::nothrow) 的巨大类声明
#include <stdio.h>
#include <stdlib.h>
#include <memory>
class Test {
int x0[0x0fffffff];
int x1[0x0fffffff];
int x2[0x0fffffff];
int x3[0x0fffffff];
int x4[0x0fffffff];
int x5[0x0fffffff];
int x6[0x0fffffff];
int x7[0x0fffffff];
int x8[0x0fffffff];
int x9[0x0fffffff];
int xa[0x0fffffff];
int xb[0x0fffffff];
int xc[0x0fffffff];
int xd[0x0fffffff];
int xe[0x0fffffff];
int xf[0x0fffffff];
public:
Test(void) {
printf("Test constructor\n");
}
void print(void) {
printf("this: %p\n", this);
}
};
int main(void) {
Test* t = new (std::nothrow) Test;
t->print();
printf("t: %p\n", t);
return 0;
}
这个的输出是:
this: 00000000
t: 00000000
显然,当new 失败时,构造函数没有被调用。
那么我如何在我的
重载new 运算符?
【问题讨论】:
标签: c++ memory-management new-operator