#include <iostream>
#include <memory>
template<typename T>
class Vector {
public:
Vector() : data(nullptr), size(0), capacity(0) {}
~Vector() {
destroy();
}
void push_back(const T& value) {
if (size == capacity) {
reserve(capacity * 2 + 1);
}
data[size++] = value;
}
void pop_back() {
if (size > 0) {
--size;
}
}
T& operator[](size_t index) {
return data[index];
}
const T& operator[](size_t index) const {
return data[index];
}
size_t getSize() const {
return size;
}
bool empty() const {
return size == 0;
}
private:
void reserve(size_t new_capacity) {
if (new_capacity <= capacity) {
return;
}
T* new_data = static_cast<T*>(operator new(sizeof(T) * new_capacity));
for (size_t i = 0; i < size; ++i) {
new (&new_data[i]) T(std::move(data[i]));
data[i].~T();
}
operator delete(data);
data = new_data;
capacity = new_capacity;
}
void destroy() {
for (size_t i = 0; i < size; ++i) {
data[i].~T();
}
operator delete(data);
data = nullptr;
size = 0;
capacity = 0;
}
private:
T* data;
size_t size;
size_t capacity;
};
上面是vector的简单实现,reserve函数中,operator new和new operator可以查看new operator和operator new,在push_back函数中,data[size++] = value调用的是=赋值函数,std调用的是拷贝构造,可以替换为以下代码既可以实现
new (&data[++size]) T(value);
测试:
class A
{
public:
A() { std::cout << "构造函数" << std::endl; }
A(const A&temp) { std::cout << "拷贝构造" << std::endl; }
A(const A&& temp) { std::cout << "移动构造" << std::endl; }
A& operator =(const A&) { std::cout << "====" << std::endl; return *this; }
};
int main() {
A a;
Vector<A> v;
v.push_back(a);
return 0;
}
输出:构造函数 拷贝构造