C ++:分配T的块而不调用构造函数 [英] C++: allocate block of T without calling constructor
问题描述
我不想调用构造函数。
我的标准方法是: :
T * data = malloc(sizeof(T)* num);
然而,我不知道if(data + i)是T-对齐。此外,我不知道这是否是正确的C ++方式。
我应该如何分配一个T块而不调用它的构造函数?
首先,你不是分配一个 T *
您正在分配一个 T
块。
其次,如果您的 / code>有一个非平凡的构造函数,然后直到元素被构造,你的块实际上不是一个T块,而是一个原始内存块。在这里不涉及
T
这一点(计算大小除外)。 A void *
指针更适合原始内存。
要分配内存,您可以使用任何您喜欢的内容。
* raw_data = malloc(num * sizeof(T));
或
void * raw_data = new unsigned char [num * sizeof(T)];
或
void * raw_data = :: operator new(num * sizeof(T));
或
std :: allocator< T>一个;
void * raw_data = a.allocate(num);
//或
// T * raw_data = a.allocate(num);
稍后,当您实际构建元素时(使用placement new,正如您所说)最后得到 T *
类型的有意义的指针,但是只要内存是原始的,使用 T *
除非你的 T
有一些异乎寻常的对齐要求,
您可能实际想看看C ++标准库提供的内存实用程序: std :: allocator<>
与分配
和构造
方法, c $ c> uninitialized_fill 等,或尝试重新发明轮子。
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?
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.
这篇关于C ++:分配T的块而不调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!