如果我重载运算符new
和delete
具有嵌套类的类:
class A
{
public:
static void* operator new(size_t);
static void operator delete(void*);
class B;
}
对象实例的A::B
分配和对象内的分配是否会A::B
使用重载A::new
和A::delete
/或全局默认值?
如果我重载运算符new
和delete
具有嵌套类的类:
class A
{
public:
static void* operator new(size_t);
static void operator delete(void*);
class B;
}
对象实例的A::B
分配和对象内的分配是否会A::B
使用重载A::new
和A::delete
/或全局默认值?
首先,您不需要超载new
也不delete
应该避免这样做的机会非常高。
除此之外,重载的运算符将应用于 class A
,而不是 class A::B
。如果您想让 B 具有重载运算符,则还需要在类中重载它们B
。
有关如何重载new
和的示例delete
: http ://www.cprogramming.com/tutorial/operator_new.html
不。
class A
{
public:
A(){printf("A\n");}
~A(){}
static void* operator new(size_t t){
printf("A new\n");
::operator new(t);
}
static void operator delete(void* t){
printf("A delete\n");
::operator delete(t);
}
void check_B(){
b = new B();
::operator delete(b);
}
class B{
public:
B(){}
};
B* b;
};
class C : public A {
};
测试:
int main(void)
{
A* a = new A;
printf("\ncheck ------\n");
a->check_B();
printf("\ncheck ------\n");
delete a;
C* c = new C;
A* cc = new C;
delete c;
delete cc;
return 0;
}
输出:
一种
新A
查看 - - -
查看 - - -
一个删除
一个新的
一种
一个新的
一种
一个删除
一个删除
运行成功(总时间:64ms)
验证:
==9318==
==9318== HEAP SUMMARY:
==9318== in use at exit: 0 bytes in 0 blocks
==9318== total heap usage: 4 allocs, 4 frees, 25 bytes allocated
==9318==
==9318== All heap blocks were freed -- no leaks are possible
==9318==
==9318== For counts of detected and suppressed errors, rerun with: -v
==9318== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
new A[]
除非您也超载,否则它甚至不会被调用operator new[]()
。您需要A::B
相应地为嵌套类重载它们。然而,正如我们所见,它们将被调用为从 A 派生的类。
测试,测试,测试。做测试总比不做测试好。作者:我。