您如何在不初始化每个元素的情况下为数组保留空间? [英] How can you reserve space for an array without initializing each element?

查看:96
本文介绍了您如何在不初始化每个元素的情况下为数组保留空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将使用默认的Foo构造函数构造10个Foo对象的数组:

The following code will construct array of 10 Foo objects with default Foo constructor:

Foo foo[10];

但是我不想这样做,我有很长的foo构造函数,以后我将一一重新定义所有foo对象并分配(将其复制)到foo数组的元素中,所以没有任何意义初始化数组,我只想为其保留空间并在以后设置它的元素.就像

but i don't want do this, i have havy foo constructor and later i will regenarate all foo objects one by one and assign (copy) it to elements of foo array, so there is no sense to initialize array, i want just reserve space for it and set it elements later. Just like in the case of

int foo[10]

如果没有= {}不会初始化foo的元素.我该如何在不使用std名称空间的情况下做到这一点(我将在不支持std的PC和CUDA上同时使用代码)?

when elements of foo will not be initialized without ={}. How can i do this without using std namespace(i will use code both on PC and CUDA that isn't supports std)?

推荐答案

您可以做所有好的动态容器所要做的事情:分别进行内存分配和对象构造.

You can do what all good dynamic containers do: separate memory allocation and object construction.

// allocate memory
char * space[10 * sizeof(Foo)];

// make sure it's aligned for our purposes
// see comments; this isn't actually specified to work
assert(reinterpret_cast<uintptr_t>(space) % alignof(Foo) == 0);

// populate 4th and 7th slots
Foo * p = ::new (space + 3 * sizeof(Foo)) Foo('x', true, Blue);
Foo * q = ::new (space + 6 * sizeof(Foo)) Foo('x', true, Blue);

// ...

// clean up when done
q->~Foo();
p->~Foo();


使用自动存储时,棘手的部分是使存储在适合于数组元素类型对齐的地址处对齐.有几种方法可以做到这一点.以后我会详细说明:


The tricky part when using automatic storage is to get storage aligned at an address suitable for the alignment of the array element type. There are several ways to accomplish this; I'll elaboate on them in the future:

  1. std :: align (感谢@Simple):

  1. std::align (thanks to @Simple):

char large_space[10 * sizeof(Foo) + 100];
std::size_t len = sizeof large_space;
void * space_ptr = large_space;

Foo * space = static_cast<Foo *>(std::align(alignof(Foo), 10 * sizeof(Foo), space, len));
assert(space != nullptr);

// construct objects in &space[i]

  • 使用 alignas

    alignas(Foo) char space[10 * sizeof(Foo)];
    

  • 使 space 成为一个合适的 std :: aligned_storage 专业化的数组(感谢@RMF)

  • Make space an array of a suitable specialization of std::aligned_storage (thanks to @RMF)

    std::aligned_storage<sizeof(Foo), alignof(Foo)>::type space[10];
    
    Foo *p = new (&space[3]) Foo('x', true, Blue);
    Foo *q = new (&space[6]) Foo('x', true, Blue);
    

  • 这篇关于您如何在不初始化每个元素的情况下为数组保留空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆