I am unable to use the STL and boost library and I have to write my own container in C++. The following code compiles without error in VC++6.
I have not actually tested the code but is concerned whether this generic container will work with both primitive and non primitive types (like class). Will there be any potential issues with the copy constructor and the assignment operator especially?
Any other suggestions and comments are most welcomed. :)
template <class T>
class __declspec(dllexport) StdVector{
private:
int _pos;
int _size;
const T *_items;
public:
StdVector();
StdVector(const StdVector &v);
StdVector(int size);
virtual ~StdVector();
void Add(const T &item);
void SetSize(int size);
int GetSize();
const T * Begin();
const T * End();
const T * ConstIterator();
StdVector & operator=(const StdVector &v);
};
template <typename T>
StdVector<T>::StdVector()
: _pos(0), _size(0), _items(NULL){
}
template <typename T>
StdVector<T>::StdVector(const StdVector &v)
: _pos(0), _size(v.GetSize()), _items(new T[_size]){
std::copy(v.Begin(), v.End(), Begin());
}
template <typename T>
StdVector<T>::StdVector(int size)
: _pos(0), _size(size), _items(new T[_size]){
}
template <typename T>
StdVector<T>::~StdVector(){
if (_items != NULL)
delete[] _items;
}
template <typename T>
void StdVector<T>::Add(const T &item){
if (_pos == _size)
throw new exception("Already at max size!!!");
_items[_pos++] = item;
}
template <typename T>
void StdVector<T>::SetSize(int size){
if (_items != NULL)
delete[] _items;
_pos = 0;
_size = size;
_items = new T[_size];
}
template <typename T>
int StdVector<T>::GetSize(){
return _size;
}
template <typename T>
const T * StdVector<T>::Begin(){
return _items;
}
template <typename T>
const T * StdVector<T>::End(){
return _items + _pos;
}
template <typename T>
const T * StdVector<T>::ConstIterator(){
return _items;
}
template <typename T>
StdVector<T> & StdVector<T>::operator=(const StdVector &v){
if (this != &v){
delete[] _items;
std::copy(v.Begin(), v.End(), Begin());
}
return *this;
}