Click here to Skip to main content
15,894,460 members

Comments by Yerasel (Top 2 by date)

Yerasel 21-Feb-12 9:17am View    
Deleted
// 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);
Yerasel 20-Feb-12 4:21am View    
I tried to define a simple Allocator following above statements. In my Allocator ::operator new() is inoked, 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 <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
template<typename u="">
struct rebind {
typedef Allocator other;
};

public :
inline explicit Allocator() {}
inline ~Allocator() {}
inline explicit Allocator(Allocator const&) {}
template<typename u="">
inline explicit Allocator(Allocator 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;
}