Nun habe ich mir mal die Größe von STL String und Vector Instanzen ausgeben lassen und bin entsetzt:
std::string -> 28 Byte
std::vector -> 24 Byte
Allein beim String kann ich mir den Content-Zeiger (32bit Maschine = 4 Byte), die Länge (4 Byte), Speichergröße (4 Byte) und den zweiten Zeiger (mit terminierender Null; 4 Byte) erklären, aber woher der restliche Speicherverbrauch? Beim Vektor sollten es sogar nur 8 Byte gesamt sein...
Nun wollte ich meine eigenen Container schreiben:
Code: Alles auswählen
template<class T>
class tinyvector{
private:
// Data
T *m_data;
size_t m_size;
size_t m_capacity;
public:
// Methods
T& at(size_t i){
return this->m_data[i];
}
size_t size(){
return this->m_size;
}
size_t capacity(){
return this->m_capacity;
}
void reserve(size_t n){
if(this->m_data){
T *new_data = new T[n];
memcpy(new_data, this->m_data, sizeof(T) * (this->m_capacity < n ? this->m_capacity : n));
delete this->m_data;
this->m_data = new_data;
}else
this->m_data = new T[n];
if(n < this->m_size)
this->m_size = n;
this->m_capacity = n;
}
void clear(){
if(this->m_data){
delete this->m_data;
this->m_data = 0;
this->m_size = 0;
this->m_capacity = 0;
}
}
void assign(const tinyvector<T>& x){
this->clear();
this->m_data = new T[x.m_capacity];
memcpy(this->m_data, x.m_data, sizeof(T) * x.m_size);
this->m_size = x.m_size;
this->m_capacity = x.m_capacity;
}
void push_back(const T& x){
if(this->m_capacity == 0)
this->reserve(1);
else if(this->m_size == this->m_capacity)
this->reserve( this->m_capacity << 1);
this->m_data[this->m_size++] = x;
}
// Operators
T& operator[](size_t i){return this->at(i);}
tinyvector<T>& operator=(const tinyvector<T>& x){this->assign(x); return *this;}
// Ctors & dtor
tinyvector() : m_data(0), m_size(0), m_capacity(0){}
explicit tinyvector(size_t n) : m_data(new T[n]), m_size(0), m_capacity(n){}
explicit tinyvector(T *data, size_t n) : m_data(data), m_size(n), m_capacity(n){}
tinyvector(const tinyvector<T>& x){this->assign(x);}
~tinyvector(){this->clear();}
};
Fehlermeldung:
Woran kann dies liegen? Worin unterscheidet sich der STL Vektor von meinem, dass er funktioniert?Problemereignisname: APPCRASH
Anwendungsname: mpc-hc.exe
Anwendungsversion: 1.5.3.3819
Anwendungszeitstempel: 4ebc2a94
Fehlermodulname: StackHash_5477
Fehlermodulversion: 6.0.6001.18538
Fehlermodulzeitstempel: 4cb733dc
Ausnahmecode: c0000374
Ausnahmeoffset: 000b0dbc
Betriebsystemversion: 6.0.6001.2.1.0.768.3
Gebietsschema-ID: 1031
Zusatzinformation 1: 5477
Zusatzinformation 2: 89ab21718fa0504e997ae585ca389584
Zusatzinformation 3: 6be0
Zusatzinformation 4: 6be4bf2306cae4afb92ab26f284e7e49