Hello,
one problem occurs with this weird push: I attach my class Person (where I use intentionally char* _sex to do the things harder). I resize the MVector on each 8 * T; I'd like to use memcpy() but with it, "Person:: operator=", doesn't start. Besides, when I delete _mem (second else branch), the local temp loose information about its _sex -> it seems _mem[]._sex and temp[]._sex refers to the same block; so I used these loop (and operator= start); but is maybe something to do better, please?
void push_back(const T val){
if ( _capacity == 0 ) {
_capacity = 8;
_mem = new T[_capacity];
_mem[_size++] = val; //first element
return;
}
if ( _size < _capacity ) {
_mem[_size++] = val;
}
else {
T* temp = new T[_capacity];
for (int i=0; i < _capacity; i++)
temp[i] = _mem[i];
//memcpy(temp, _mem, sizeof(T) * _capacity);
int oldCapacity = _capacity;
_capacity += 8;
delete []_mem;
_mem = new T[_capacity];
//memcpy(_mem, temp, sizeof(T) * oldCapacity);
for (int i=0; i < oldCapacity; i++)
_mem[i] = temp[i];
delete []temp;
_mem[_size++] = val;
}
}
//main.cpp
MVector<Person> p(1);
p.push_back( Person ("mike", 99, 'M') );
.............................................
void push_back(const T val){
if ( _capacity == 0 ) {
_capacity = 8;
_mem = new T[_capacity];
_mem[_size++] = val; //first element
return;
}
if ( _size < _capacity ) {
_mem[_size++] = val;
}
else {
T* temp = new T[_capacity];
for (int i=0; i < _capacity; i++)
temp[i] = _mem[i];
//memcpy(temp, _mem, sizeof(T) * _capacity);
int oldCapacity = _capacity;
_capacity += 8;
delete []_mem;
_mem = new T[_capacity];
//memcpy(_mem, temp, sizeof(T) * oldCapacity);
for (int i=0; i < oldCapacity; i++)
_mem[i] = temp[i];
delete []temp;
_mem[_size++] = val;
}
}
//main.cpp
MVector<Person> p(1);
p.push_back( Person ("mike", 99, 'M') );
.............................................
To copy to clipboard, switch view to plain text mode
Bookmarks