开发者

C++: allocate block of T without calling constructor

开发者 https://www.devze.com 2022-12-22 10:43 出处:网络
I don\'t want constructor called. I am using placement new. I just want to allocate a block of T. My standard approach is:

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 = mallo开发者_如何学Cc(sizeof(T) * num);

however, I don't know if (data+i) is T-aligned. Furthermore, I don't know if this is the right "C++" way.

How should I allocate a block of T without calling its constructor?


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消