Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: allocate block of T without calling constructor

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(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?

like image 509
anon Avatar asked Mar 04 '10 21:03

anon


2 Answers

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.

like image 114
AnT Avatar answered Oct 02 '22 17:10

AnT


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.

like image 42
Jerry Coffin Avatar answered Oct 02 '22 16:10

Jerry Coffin