I tried to define a simple Allocator following above statements. In my Allocator ::operator new() is invoked, and than I define vector. However it turns out that vector will call overloaded new and delete if these operators are overloaded globally.
The code as following:
#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");
if (!mem) puts("out");
return mem;
}
void operator delete(void* mem)
{
puts("My free");
free(mem);
}
template<typename t="">
class Allocator {
public :
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 :
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&) {}
inline pointer address(reference r) { return &r; }
inline const_pointer address(const_reference r) { return &r; }
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);
}
inline size_type max_size() const {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
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); }
};
int main()
{
int* test1 = new int(10);
int* test2 = new int[5];
vector<int,> > intvec;
vector<int,> >::iterator it;
intvec.insert(it, 10);
delete test1;
delete []test2;
return 0;
}