练习new和delete

比较懒,把方法都写在类里面了。

template <class Type>
class Vector2
{
public:
Vector2(): element(0), first_free(0), end(0)
{
}
~Vector2()
{
operator delete[](element);
}
void push_back(const Type& t)
{
if(first_free==end)
{
reallocate();
}
new (first_free) Type (t);
first_free++;
}
Type operator[](int index)
{
return *(element+index);
}

Type* begin()
{
return element;
}
Type* End()
{
return first_free;
}

class Iterator
{
public:
Iterator(): currentPos(0){};
Iterator& operator=(Type* t)
{
currentPos=t;
return *this;
}
~Iterator(){};

Iterator& operator++()
{
++currentPos;
return *this;
}

Type& operator*()
{
return *currentPos;
}

Iterator operator++(int)
{
Iterator ret(*this);
++(*this);
return ret;
}

bool operator==(Type* pt)
{
return currentPos==pt;
}

bool operator!=(Type* pt)
{
return currentPos!=pt;
}
private:
Type* currentPos;
};
private:
void reallocate()
{
std::ptrdiff_t size=first_free-element;
std::ptrdiff_t newsize=2*max(first_free-element, 1);
Type* newelements=static_cast<Type*>(operator new[](newsize*sizeof(Type)));
uninitialized_copy(element, first_free, newelements);
for(Type* p=first_free; p!=element; )
{
(--p)->~Type();
}
operator delete[](element);
element=newelements;
first_free=element+size;
end=element+newsize;
}
Type* element;
Type* first_free;
Type* end;
};

你可能感兴趣的:(delete)