全局重载new和delete之后能否在STL中使用默认的new和delete

在全局重载操作符new和delete之后,STL也会受其影响,不能调用系统默认的new和delete了。

另外,及时使用Allocator也不管用了,还是overload版的new。示例程序如下:

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <stdio.h>
#include <limits>
using namespace std;

void* operator new(size_t s)
{
    void* mem = malloc(s);
    puts("My new");

    // avoid using iostream, for it will use new & delete,that will lead to deadlock
    if (!mem) puts("out");

    return mem;
}

void operator delete(void* mem)
{
    puts("My free");
    free(mem);
}

template<typename T>
class Allocator {
public :
    //    typedefs
    typedef T value_type;
    typedef value_type* pointer;
    typedef const value_type* const_pointer;
    typedef value_type& reference;
    typedef const value_type& const_reference;
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;

public :
    //    convert an allocator<T> to allocator<U>
    template<typename U>
    struct rebind {
        typedef Allocator<U> other;
    };

public :
    inline explicit Allocator() {}
    inline ~Allocator() {}
    inline explicit Allocator(Allocator const&) {}
    template<typename U>
    inline explicit Allocator(Allocator<U> const&) {}

    //    address
    inline pointer address(reference r) { return &r; }
    inline const_pointer address(const_reference r) { return &r; }

    //    memory allocation
    inline pointer allocate(size_type cnt,
       typename std::allocator<void>::const_pointer = 0) {
      return reinterpret_cast<pointer>(::operator new(cnt * sizeof (T)));
    }
    inline void deallocate(pointer p, size_type) {
        ::operator delete(p);
    }

    //    size
    inline size_type max_size() const {
        return std::numeric_limits<size_type>::max() / sizeof(T);
 }

    //    construction/destruction
    inline void construct(pointer p, const T& t) { new(p) T(t); }
    inline void destroy(pointer p) { p->~T(); }

    inline bool operator==(Allocator const&) { return true; }
    inline bool operator!=(Allocator const& a) { return !operator==(a); }
};    //    end of class Allocator

int main()
{
    // they all invoke overload new and delete
    int* test1 = new int(10);
    int* test2 = new int[5];
    vector<int, Allocator<int> > intvec;
    vector<int, Allocator<int> >::iterator it;
    intvec.insert(it, 10);

    delete test1;
    delete []test2;
    return 0;
}


另外,new和delete不能定义在某个namespace中,示例如下:

int* ptr = 0;

namespace X {
    void* operator new (size_t);
    void operator delete(void*);
    void f()
    {
       ptr = new int();
    }
}

void f()
{
    delete ptr;
    ptr = 0;
}
ptr如何被析构呢?是全局operator delete()还是namespace X中的?C++无法推断,因此不允许这样做。



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值