C++ vector that *doesn't* initialize its members?

前端 未结 5 950
别那么骄傲
别那么骄傲 2020-12-07 13:08

I\'m making a C++ wrapper for a piece of C code that returns a large array, and so I\'ve tried to return the data in a vector.

Now t

5条回答
  •  天命终不由人
    2020-12-07 14:13

    The optimal solution is to simply change the allocator to do nothing for a zero-arguments construct. This means that the underlying type is the same, which dodges any kind of nasty reinterpret_casting and potential aliasing violations and can non-intrusively uninitialize any type.

    template struct no_initialize : std::allocator {
        void construct(T* p) {}
        template void construct(T* p, Args&&... args) {
            new (p) T(std::forward(args)...);
        }
    };
    

提交回复
热议问题