可能吗?std::vector<double> my_vec(sz);已分配但未初始化或填充

Is it possible? std::vector<double> my_vec(sz); which is allocated but not initialized or filled

本文关键字:sz 分配 填充 初始化 vec my std vector lt gt double      更新时间:2023-10-16

at [C 11中的值initialized对象和std :: vector构造函数,channel72问,

问题:我的理解在这里正确吗?如果T是POD?

答案是否。

我的问题是,"好吧,那是什么?"

Nevin的回答之一暗示了回答我的问题。要澄清,我的问题是,有没有一种方法可以使用std :: vector&lt; double>,而无需免费填充分配的内存或其他?

我不是在要求解决方法,例如以零大小和使用push_back()启动矢量。这并不总是可能,而且此时,我想把它弄清楚,除了我想弄清楚它之外。

我无法获得Nevin的建议,一种自定义分配器的建议。VC 2017RC(Dinkum)以通常难以理解的方式投诉。关于std :: _ wrap_alloc的东西。Nevin的代码不完整,我可能不知道如何完成它。在我看到他的之前,我写了自己的自定义分配器,但我对自己的理解不足以发誓。

在我对此感到困惑的那段时间里,我本可以为STD :: Vector写一个不太教条的替代品,以及《美国伟大小说》的几章。

hooray!理查德·克里(Richard Critten)进行救援!他在问题下的评论直接导致答案。

零刺激罪魁祸首是默认的分配模板,即std ::分配器。因此,我们替换它,或用分配器适配器对其进行修改。

我对代码进行了一些整理,并扩展了评论。比尔,请随时发布更全面的答案。但是以下功能非常好。

// Allocator adapter
// Given an allocator A, (std::allocator by default), this adapter 
// will, when feasible, override A::construct() with a version that 
// employs default construction rather than value-initialization.
// "Feasible" means the object (U *ptr) is default-constructable and
// the default constructor cannot throw exceptions.
// 
// Thus it thwarts gratuitous initializations to zeros or whatever.
template <typename T, typename A = std::allocator<T>>
class default_init_allocator : public A {
    typedef std::allocator_traits<A> a_t;
public:
    // http://en.cppreference.com/w/cpp/language/using_declaration
    using A::A; // Inherit constructors from A
    template <typename U> struct rebind {
        using other =
            default_init_allocator
            <  U, typename a_t::template rebind_alloc<U>  >;
    };
    template <typename U>
    void construct(U* ptr)
        noexcept(std::is_nothrow_default_constructible<U>::value) {
        ::new(static_cast<void*>(ptr)) U;
    }
    template <typename U, typename...Args>
    void construct(U* ptr, Args&&... args) {
        a_t::construct(static_cast<A&>(*this),
            ptr, std::forward<Args>(args)...);
    }
};

尚未尝试过,但是从一些谷歌搜索中,似乎可以通过为std :: vector提供自定义分配器来做到这一点。查看最后一行https://en.cppreference.com/w/cpp/named_req/defaultinsertable

如果价值定位不良,例如,如果对象是非类型的类型,并且不需要零,则可以通过提供自定义分配器:: construct

来避免它。

您可以用具有分配的内存的数组初始化向量。

Type* typeArray = new Type [size];
vector <Type> typeVec (typeArray, typeArray+size);

这将为您提供分配的内存(虽然这是垃圾),并且您必须谨慎访问它,因为它可以允许您致电 typevec [n] .typeval除非您实际在n

处初始初始化了值,否则它可能会产生不确定的行为。

或如果类型是非类型的类型,则该值在n处是剩下的任何东西的值