If I overload operators new and delete for a class with a nested class:

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

    class B;
}

Will allocations for instances of A::B objects and allocations within A::B objects use the overloaded A::new and A::delete or the global defaults?

有帮助吗?

解决方案

First of all, chances are very high that you do not need to overload new nor delete and should avoid doing so.

Baring that, the overloaded operators are going to apply to class A, not to class A::B. If you wanted to have B with overloaded operators, you would need to overload them in class B as well.

For an example of how to overload new and delete: http://www.cprogramming.com/tutorial/operator_new.html

其他提示

No.

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 {

};

test:

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;
}

output:

A

new A

check ------

check ------

A delete

A new

A

A new

A

A delete

A delete

RUN SUCCESSFUL (total time: 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)

It won't be even called for new A[] unless you overload operator new[]() as well. You need to overload them for nested class A::B accordingly. However as we see they will be called for classes derived from A.

Test, test, test. Do the test is always better than not do the test. Author: me.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top