The below code gives an output of:
Allocated!
Allocated!
Deleted!
Allocated!
Allocated!
Deleted!
Size: 3
Capacity: 4
vector[0]: isAligned!
20
30
40
Deleted!
Deleted!
Can someone explain the first allocation and why there are 4 allocations instead of 2 (one for each reserve?). I figure the first is because the vector stores some memory before when created but why there are two after the first reserve instead of one baffles me. (Even without the second reserve its there just was testing to make sure all the copying and stuff worked fine since this is my first time using an allocator in a template)
//Custom Allocator
#include <memory>
#include <allocators>
#include <iostream>
template<typename T>
class Allocator16
{
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 Allocator16<U> other;
};
public:
inline Allocator16(){}
inline ~Allocator16(){}
inline Allocator16(Allocator16 const&){}
template<typename U>
inline explicit Allocator16(Allocator16<U> const&){}
//address
inline reference 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)
{ std::cout << "Allocated!" << std::endl;
return (T*)_aligned_malloc(sizeof(T)*cnt,16);}
inline void deallocate(pointer p,size_type)
{
std::cout << "Deleted!" << std::endl;
_aligned_free(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==(Allocator16 const&){return true;}
inline bool operator!=(Allocator16 const& s){return !operator==(s);}
};
//Main Code
using namespace std;
template<typename T>
class Aligned16Vector : public vector<T,Allocator16<T>>
{
public:
Aligned16Vector(void)
{
vector<T,Allocator16<T>>::vector();
}
};
bool isAligned(void* p)
{
if(((unsigned long)p & 15) == 0)
return true;
return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
Aligned16Vector<float> myVector;
myVector.reserve(4);
myVector.push_back(20.0f);
myVector.push_back(30.0f);
myVector.push_back(40.0f);
myVector.reserve(10);
std::cout << "Size: " << myVector.size() << std::endl;
std::cout << "Capacity: " << myVector.capacity() << std::endl;
if(isAligned(&myVector[0]))
std::cout << "vector[0]: isAligned!" << std::endl;
if(isAligned(&myVector[1]))
std::cout << "vector[1]: isAligned!" << std::endl;
for(int i = 0; i < myVector.size();)
{
cout << myVector[i++] << endl;
}
myVector.~Aligned16Vector();
std::cout << "Size: " << myVector.size() << std::endl;
unsigned char c = 0;
do
{
cin >> c;
}while(c != 'q');
return 0;
}