如果我为具有嵌套类的类重载运算符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
或全局默认值?
答案 0 :(得分:3)
首先,您不需要重载new
或delete
,并且应该避免这样做,这可能性非常高。
Baring that,重载的运算符将应用于类A
,而不是类A::B
。如果您希望B具有重载运算符,则还需要在类B
中重载它们。
有关如何重载new
和delete
的示例:http://www.cprogramming.com/tutorial/operator_new.html
答案 1 :(得分:1)
没有
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
新A
检查------
检查------
删除
新的
A
新的
A
删除
删除
RUN SUCCESSFUL(总时间:64ms)
的valgrind:
==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的类。
测试,测试,测试。测试总是优于不测试。作者:我。