C++: allocate block of T without calling constructor

前端 未结 3 671
野趣味
野趣味 2021-02-01 04:01

I don\'t want constructor called. I am using placement new.

I just want to allocate a block of T.

My standard approach is:

T* data = malloc(sizeo         


        
相关标签:
3条回答
  • 2021-02-01 04:23

    Firstly, you are not allocating a "block of T*". You are allocating a "block of T".

    Secondly, if your T has non-trivial constructor, then until elements are constructed, your block is not really a "block of T", but rather a block of raw memory. There's no point in involving T here at all (except for calculating size). A void * pointer is more appropriate with raw memory.

    To allocate the memory you can use whatever you prefer

    void *raw_data = malloc(num * sizeof(T));
    

    or

    void *raw_data = new unsigned char[num * sizeof(T)];
    

    or

    void *raw_data = ::operator new(num * sizeof(T));
    

    or

    std::allocator<T> a;
    void *raw_data = a.allocate(num);
    // or
    // T *raw_data = a.allocate(num);
    

    Later, when you actually construct the elements (using placement new, as you said), you'll finally get a meaningful pointer of type T *, but as long as the memory is raw, using T * makes little sense (although it is not an error).

    Unless your T has some exotic alignment requirements, the memory returned by the above allocation functions will be properly aligned.

    You might actually want to take a look at the memory utilities provided by C++ standard library: std::allocator<> with allocate and construct methods, and algorithms as uninitialized_fill etc. instead or trying to reinvent the wheel.

    0 讨论(0)
  • 2021-02-01 04:42

    T* data = reinterpret_cast<T*>(operator new(sizeof(T) * num));

    Or just use std::vector<T> and don't worry about these low-level memory details ;)

    0 讨论(0)
  • 2021-02-01 04:48

    The return from malloc is aligned for any type, so that's not a problem.

    Generally in C++, ::operator new would be the preferred way. You might also consider using an Allocator<T>, which gives some extra flexibility (like being able to switch allocators easily.

    0 讨论(0)
提交回复
热议问题