简体   繁体   English

每个 class 实例具有不同大小的数组 class 成员

[英]array class member with different size for each class instance

I would like to have a class that contains an array member, but the constructor lets me set the size of an array member.我想要一个包含数组成员的 class,但构造函数允许我设置数组成员的大小。

Is this doable?这是可行的吗? I do not thing I need dynamic allocation, since once the class instances are created, there is no need for the array to change size, it is just that each class instance will have a different size.我不需要动态分配,因为一旦创建了 class 实例,就不需要更改数组的大小,只是每个 class 实例的大小不同。

Despite several comments suggest that this would be impossible, it is actually not impossible.尽管有一些评论表明这是不可能的,但实际上并非不可能。

The simplest way, of course, is to use an indirection and allocate the array during construction just the normal way (with a = new type[size] and calling delete[] a - not delete a - in the destructor).当然,最简单的方法是使用间接方法并在构造期间以正常方式分配数组(使用a = new type[size]并在析构函数中调用delete[] a -而不是delete a -)。

But if for some reason you really do not want to have the array data being allocated separately from your object, you can use placement-new to construct your object into a pre-allocated buffer that is large enough to contain all your elements.但是如果出于某种原因你真的不想让数组数据与你的 object 分开分配,你可以使用placement-new 将你的 object 构造成一个足够大以包含所有元素的预分配缓冲区。 This avoids a separate allocation for your array and you can still have dynamic size.这避免了为您的数组单独分配,并且您仍然可以拥有动态大小。

I would not recommend using this technique, though, unless you really have a demanding use case for it.不过,我不推荐使用这种技术,除非你真的有一个要求很高的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM