编辑代码

#include <vector>
#include <memory>
#include <iostream>
#include <chrono>

using namespace std::literals;

template <typename T>
class no_init_allocator {
public:
    using value_type = T;
    no_init_allocator() = default;
    
    T* allocate(size_t n) {
        return reinterpret_cast<T*>(operator new(n));
    }
    void deallocate(T* ptr, size_t n) {
        operator delete(ptr);
    }
    
    template<typename U>
    void construct(U*) {}
    template <typename U, typename... Args>
    void construct(U* ptr, Args&&... args) {
        new(ptr) U{std::forward<Args>(args)...}; 
    }
};

int main() {
    using clock = std::chrono::high_resolution_clock;

    auto no_init_start = clock::now();
    std::vector<int, no_init_allocator<int>> vec_a(1000000);
    auto no_init_end = clock::now();
    std::cout << (no_init_end - no_init_start) / 1ns << "ns ";

    auto std_start = clock::now();
    std::vector<int, std::allocator<int>>    vec_b(1000000);
    auto std_end = clock::now();
    std::cout << (std_end - std_start) / 1ns << "ns\n";

    return 0;
}