关于嵌套类的运算符new的重载解析

Overload resolution of operator new regarding nested classes

本文关键字:运算符 new 重载 于嵌套 嵌套      更新时间:2023-10-16

如果我为具有嵌套类的类重载运算符newdelete

class A
{
public:
    static void* operator new(size_t);
    static void operator delete(void*);
    class B;
}

A::B对象实例的分配和A::B对象内的分配会使用重载的A::newA::delete还是全局默认值?

首先,您不需要过载newdelete的可能性非常高,并且应该避免这样做。

尽管如此,重载运算符将应用于类A,而不是类A::B。如果您希望B具有重载运算符,那么还需要在类B中重载它们。

关于如何过载newdelete的示例:http://www.cprogramming.com/tutorial/operator_new.html

否。

class A
{
public:
    A(){printf("An");}
    ~A(){}
    static void* operator new(size_t t){
        printf("A newn");
        ::operator new(t);
    }
    static void operator delete(void* t){
        printf("A deleten");
        ::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;
}

输出:

新的

检查------

检查------

删除

一种新的

一种新的

删除

删除

运行成功(总时间: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.派生的类

测试,测试,测试。做测试总比不做测试好。作者:me.