跳到正文

剪贴板

剪贴板 n0pegsd0

原文
剪贴板信息

剪贴板信息

收录
更新
C++
#include <iostream>
#include <iterator>
#include <memory>
#include <new>
#include <type_traits>
#include <vector>

struct A {
    int value{};

    A() { std::cout << "Default Construct\n"; }
    ~A() { std::cout << "Destroy" << value << '\n'; }
    A(int value): value{value} { std::cout << "Construct" << value << '\n'; }
    A(A const &other): value{other.value} { std::cout << "Copy Construct" << value << '\n'; }
    A(A &&other) noexcept: value{other.value} { std::cout << "Move Construct" << value << '\n'; }

    auto operator= (A const &other) -> A & {
        std::cout << "Copy Assign" << value << ' ' << other.value << '\n';
        value = other.value;
        return *this;
    }
    auto operator= (A &&other) noexcept -> A & {
        std::cout << "Move Assign" << value << ' ' << other.value << '\n';
        value = other.value;
        return *this;
    }
};

namespace mystd {
template <typename T>
class vector {
private:
    T *data_ = nullptr;
    std::size_t size_ = 0;
    std::size_t capacity_ = 0;

    using iterator = T *;
    using const_iterator = T const *;
    using value_type = T;
public:
    constexpr vector() = default;
    constexpr ~vector() {
        destroy_all();
    }

    explicit constexpr vector(std::size_t count)
        : data_(allocate(count)), capacity_(count)
    {
        try {
            for (T *ptr = data(); size_ != count; ++size_, ++ptr) {
                std::construct_at(ptr);
            }
        } catch (...) {
            // 构造失败,销毁资源并释放内存(异常安全)
            destroy_all();  // 由于 size_ 是当前元素数量,可以直接使用
            throw;  // 重新抛出异常
        }
    }
    constexpr vector(std::size_t count, T const &value)
        : data_(allocate(count)), capacity_(count)
    {
        try {
            for (T *ptr = data_; size_ != count; ++size_, ++ptr) {
                std::construct_at(ptr, value);
            }
        } catch (...) {
            destroy_all();
            throw;
        }
    }
    // 复制构造函数
    constexpr vector(vector const &other)
        : data_(allocate(other.size())), capacity_(other.size())
    {
        try {
            T const *in = other.data();
            T *out = data();
            for (; size_ != other.size(); ++size_, ++in, ++out) {
                std::construct_at(out, *in);
            }
        } catch (...) {
            destroy_all();
            throw;
        }
    }

    // 移动构造函数
    constexpr vector(vector &&other) noexcept
        : data_(other.data()), size_(other.size()), capacity_(other.capacity())
    {
        // 将另一个容器置空,避免内存多次释放
        other.data_ = nullptr;
        other.size_ = other.capacity_ = 0;
    }

    // 接受一个范围内的数据
    template <typename InputIt>
    constexpr vector(InputIt first, InputIt last): vector() {
        // 如果是 ForwardIterator,预先获取区间大小;否则依次 emplace_back
        using category = typename std::iterator_traits<InputIt>::iterator_category;
        constexpr bool is_forward = std::is_base_of_v<std::forward_iterator_tag, category>;

        if constexpr (is_forward) {
            std::size_t size = std::distance(first, last);
            reserve(size);
        }

        for (; first != last; ++first) {
            emplace_back(*first);
        }
    }

    // std::initializer_list
    constexpr vector(std::initializer_list<T> list)
        : vector(list.begin(), list.end()) {}

    auto constexpr size() const noexcept -> std::size_t { return size_; }
    auto constexpr capacity() const noexcept -> std::size_t { return capacity_; }
    auto constexpr data() noexcept -> T * { return data_; }

    // begin() end() 需要同时提供 const 和非 const 版本
    auto constexpr begin() const noexcept -> const_iterator { return data_; }
    auto constexpr end() const noexcept -> const_iterator { return data_ + size_; }
    auto constexpr begin() noexcept -> iterator { return data_; }
    auto constexpr end() noexcept -> iterator { return data_ + size_; }


    auto constexpr back() const -> T const & { return data_[size() - 1]; }
    auto constexpr front() const -> T const & { return data_[0]; }
    auto constexpr back() -> T & { return data_[size() - 1]; }
    auto constexpr front() -> T & { return data_[0]; }

    template <typename ...Ts>
    auto constexpr emplace_back(Ts &&...args) -> T & {
        // 检查是否需要扩容
        if (size() == capacity()) {
            // 执行扩容
            // 分配一片新的内存
            auto new_capacity = capacity() == 0? 1: capacity() * 2;
            auto new_data = allocate(new_capacity);
            // 直接构造新对象
            auto pos = new_data + size();
            std::construct_at(pos, std::forward<Ts>(args)...);
            // 逐个移动现有元素
            // 但是此处需要注意,仅当移动构造为 noexcept 才能保证强异常安全
            // 否则如果在某个元素移动时抛出异常,将会永久丢失它的状态,无法保证回退
            // 标准库的处理是,如果不能安全地移动,就使用拷贝构造。
            T *in = data();
            T *out = new_data;
            try {
                for (std::size_t i = 0; i != size(); ++i, ++in, ++out) {
                    if constexpr (std::is_nothrow_move_constructible_v<T>) {
                        std::construct_at(out, std::move(*in));
                    } else {
                        std::construct_at(out, *in);
                    }
                }
            } catch (...) {
                // 销毁刚构造的新元素
                std::destroy_at(pos);
                for (auto ptr = new_data; ptr != out; ++ptr) {
                    std::destroy_at(ptr);
                }
                deallocate(new_data, new_capacity);
                throw;
            }
            // 释放旧数据
            destroy_all();
            data_ = new_data, capacity_ = new_capacity;
        } else {
            // 直接在结尾构造
            auto pos = data() + size();
            std::construct_at(pos, std::forward<Ts>(args)...);
        }
        ++size_;
        return back();
    }

    auto constexpr push_back(T const &x) -> void {
        emplace_back(x);
    }

    auto constexpr push_back(T &&x) -> void {
        emplace_back(std::move(x));
    }

    auto constexpr reserve(std::size_t new_cap) -> void {
        if (new_cap <= capacity()) return;
        auto new_data = allocate(new_cap);

        // 和 emplace_back 相同逻辑,决定移动还是复制
        T *in = data();
        T *out = new_data;
        try {
            for (auto end_ptr = data() + size(); in != end_ptr; ++in, ++out) {
                if constexpr (std::is_nothrow_move_constructible_v<T>) {
                    std::construct_at(out, std::move(*in));
                } else {
                    std::construct_at(out, *in);
                }
            }
        } catch (...) {
            for (auto ptr = new_data; ptr != out; ++ptr) {
                std::destroy_at(ptr);
            }
            deallocate(new_data, new_cap);
            throw;
        }

        destroy_all();
        data_ = new_data;
        capacity_ = new_cap;
    }

    // 这里采取了一种简化的实现方法,按值传参,在内部统一移动
    // 对于 std::array 这类移动开销大的对象可能性能较差
    // 标准库分别实现了 T const & 和 T &&,更加健壮
    // 标准库 insert 没有强异常安全的保证,所以可以直接使用移动赋值和构造
    auto constexpr insert(const_iterator pos, T value) -> iterator {
        std::size_t index = pos - begin();
        if (size() == capacity()) {
            // 扩容的同时移动数据
            auto new_capacity = capacity() == 0? 1: capacity() * 2;
            auto new_data = allocate(new_capacity);

            T *in = data();
            T *out = new_data;
            try {
                for (; in != pos; ++in, ++out) {
                    // 内存位置尚未构造对象,所以使用构造而非赋值
                    std::construct_at(out, std::move(*in));
                }
                std::construct_at(out, std::move(value)), ++out;
                for (auto end_ptr = data() + size(); in != end_ptr; ++in, ++out) {
                    std::construct_at(out, std::move(*in));
                }
            } catch (...) {
                // 出现异常,保证无资源泄漏即可
                for (auto ptr = new_data; ptr != out; ++ptr) {
                    std::destroy_at(ptr);
                }
                deallocate(new_data, new_capacity);
                throw;
            }

            destroy_all();
            data_ = new_data, capacity_ = new_capacity;
            ++size_;
        } else {
            // 直接移动数据
            // 最后一个元素使用构造,其他元素使用赋值
            T *out = data() + size();
            // 结尾插入元素,直接构造即可
            if (pos == end()) {
                std::construct_at(out, std::move(value));
                ++size_;
            } else {
                T *in = std::prev(out);
                std::construct_at(out, std::move(*in)), --out, --in;
                ++size_;
                // 此后如果抛出异常,可以保证容器基本信息(size_)正确,但是容器内数据处于未指定状态
                for (; out != pos; --out, --in) {
                    // 当这个位置已经有了一个对象,应当使用赋值
                    // 否则应当是先销毁再构造,但是用户定义的赋值可能更加高效
                    *out = std::move(*in);
                }
                // 此时 out 的位置上同样已经存在对象
                // 通过赋值放置新对象
                *out = std::move(value);
            }
        }
        return begin() + index;  // 转换成非常量迭代器
    }

    auto constexpr operator[] (std::size_t pos) -> T & {
        return data_[pos];
    }
    // 同时提供常量的只读下标访问
    auto constexpr operator[] (std::size_t pos) const -> T const & {
        return data_[pos];
    }

    // 交换两个 vector
    auto constexpr swap(vector &other) noexcept -> void {
        std::swap(data_, other.data_);
        std::swap(size_, other.size_);
        std::swap(capacity_, other.capacity_);
    }
    // 提供非成员的 swap,允许 ADL 查找
    auto friend constexpr swap(vector &lhs, vector &rhs) noexcept -> void {
        lhs.swap(rhs);
    }
    // 复制赋值
    auto constexpr operator= (vector const &other) -> vector & {
        if (this == &other) return *this;  // 避免自赋值
        vector<T> tmp(other);  // 构造临时对象
        swap(tmp);  // 直接和临时对象交换,复用代码且异常安全
        return *this;
    }
    // 移动赋值
    auto constexpr operator= (vector &&other) noexcept -> vector & {
        vector<T> tmp(std::move(other));  // 移动构造一个临时对象,other 直接置空
        swap(tmp);  // 和临时对象交换,旧资源将在 tmp 销毁时释放
        // 可以证明,这种方式对于自赋值是安全的
        return *this;
    }
private:
    // 分配未初始化内存,足以存储 n 个 T 类型
    auto constexpr static allocate(std::size_t n) -> T * {
        if (n == 0) return nullptr;
        if (std::is_constant_evaluated()) {
            // 编译器开洞实现 std::allocator,可以在编译期动态分配内存
            // 正常的常量求值无法使用 ::operator new
            return std::allocator<T>{}.allocate(n);
        } else {
            // 显式指定对象对齐,允许非标准对齐的对象
            auto ptr = ::operator new(n * sizeof(T), std::align_val_t{alignof(T)});
            return static_cast<T *>(ptr);
        }
    }

    // 释放 allocate 分配的内存
    auto constexpr static deallocate(T *ptr, std::size_t n) noexcept -> void {
        if (ptr == nullptr) return;
        if (std::is_constant_evaluated()) {
            std::allocator<T>{}.deallocate(ptr, n);
        } else {
            ::operator delete(ptr, std::align_val_t{alignof(T)});
        }
    }

    // 销毁所有元素,释放资源
    auto constexpr destroy_all() noexcept -> void {
        T *ptr = data();
        for (std::size_t i = 0; i != size(); ++i, ++ptr) {
            std::destroy_at(ptr);
        }
        deallocate(data(), capacity());
    }
};
}


auto main() -> int {
    mystd::vector<A> vec{0, 1, 2, 3, 4, 5};
    vec.insert(vec.begin() + 3, 666);
    for (auto const &x: vec) std::cout << x.value << " ";
}