在全局重载操作符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++无法推断,因此不允许这样做。