Exceptional C++

【Exceptional C++(20)】内存管理(二)

2018-01-30  本文已影响13人  downdemo

问题

class B {
public:
    virtual ~B();
    void operator delete(void*, size_t) throw();
    void operator delete[](void*, size_t) throw();
    void f(void*, size_t) throw();
};
class D : public B {
public:
    void operator delete(void*) throw();
    void operator delete[](void*) throw();
};
void f()
{
    // 下列语句中调用的是哪个delete
    // 调用时的参数是什么
    D* pd1 = new D;
    delete pd1;
    B* pb1 = new D;
    delete pb1;
    D* pd2 = new D[10];
    delete[] pd2;
    B* pb2 = new D[10];
    delete[] pb2;
    // 下面两个赋值语句合法吗?
    B b;
    typedef void (B::*PMF)(void*, size_t);
    PMF p1 = &B::f;
    PMF p2 = &B::operator delete;
}
class X {
public:
    void* operator new(size_t s, int)
    throw(bad_alloc) {
        return ::operator new(s);
    }
};
class SharedMemory {
public:
    static void* Allocate(size_t s) {
        return OsSpecificSharedMemAllocation(s);
    }
    static void Deallocatate(void* p, int i) {
        OsSpecificSharedMemDeallocation(p, i);
    }
};
class Y {
public:
    void* operator new(size_t s, SharedMemory& m)
    throw(bad_alloc) {
        return m.Allocate(s);
    }
    void operator delete(void* p, SharedMemory& m, int i)
    throw() {
        m.Deallocate(p, i);
    }
};
void operator delete(void* p) throw() {
    SharedMemory::Deallocate(p);
}
void operator delete(void* p, std::nothrow_t&) throw() {
    SharedMemory::Deallocate(p);
}

解答

    D* pd1 = new D;
    delete pd1; // D::operator delete(void*)
    B* pb1 = new D;
    delete pb1; // D::operator delete(void*)
    D* pd2 = new D[10];
    delete[] pd2; // D::operator delete[](void*)
    B* pb2 = new D[10];
    delete[] pb2; // 不可预料的行为
    // 传递给delete的指针静态类型必须与动态类型一样
    B b;
    typedef void (B::*PMF)(void*, size_t);
    PMF p1 = &B::f;
    PMF p2 = &B::operator delete;
class X {
public:
    void* operator new(size_t s, int)
    throw(bad_alloc) {
        return ::operator new(s);
    }
};
class SharedMemory {
public:
    static void* Allocate(size_t s) {
        return OsSpecificSharedMemAllocation(s);
    }
    static void Deallocatate(void* p, int i) {
        OsSpecificSharedMemDeallocation(p, i);
    }
};
class Y {
public:
    void* operator new(size_t s, SharedMemory& m)
    throw(bad_alloc) {
        return m.Allocate(s);
    }
SharedMemory shared;
...
new (shared) T; // if T::T() throws, memory is leaked
    void operator delete(void* p, SharedMemory& m, int i)
    throw() {
        m.Deallocate(p, i);
    }
};

这个delete完全没用,因为它从不会被调用

void operator delete(void* p) throw() {
    SharedMemory::Deallocate(p);
}
void operator delete(void* p, std::nothrow_t&) throw() {
    SharedMemory::Deallocate(p);
}
上一篇下一篇

猜你喜欢

热点阅读