vector源码剖析

#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;
}

输出:构造函数 拷贝构造

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

vegetablesssss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值