简体   繁体   English

如何在没有动态内存分配的情况下创建对象数组

[英]how to create array of objects without dynamic memory allocation

I got following code, where 100 objects are created in a loop. 我得到了以下代码,其中在循环中创建了100个对象。

My question is, 我的问题是,

  • why do I need the use new here, because i already know beforehand how much memory i need. 为什么我需要在这里使用new ,因为我事先已经知道我需要多少内存。
  • is there a code which does the same as my example code, without dynamic memory allocation? 是否有一个代码与我的示例代码相同,没有动态内存分配? (and without using std containers such as vector ) (...class + dynamic momery together is getting confusing) (并且不使用vector等std容器)(...类+动态momery一起变得混乱)

example code: 示例代码:

class Particle {...};
Particle *myParticles[ 100 ];

for( int i = 0; i < 100; i++ )
{   
    myParticles[ i ] = new Particle(x,y);          //x and y are randomized for each loop
}

[UPDATE]: class Particle does not have a default constructor. [UPDATE]: class Particle没有默认构造函数。 Hence Particle myParticles[ 100 ]; 因此, Particle myParticles[ 100 ]; will not work. 不管用。 Note that, there is a work around by setting up a default constructor, and then creating methods Particle::setXY (double x, double y) . 请注意,通过设置默认构造函数,然后创建方法Particle::setXY (double x, double y)

But is there a way to solve this without creating new methods?? 但有没有办法解决这个问题,而无需创建新方法? ie only using constructor, and no dynamic memory allocation. 即仅使用构造函数,并且没有动态内存分配。

I just find it strange, that this cannot be done(?) without dynamic memory allocation. 我觉得很奇怪,没有动态内存分配就无法完成(?)。 Or do I have to accept the fact that this just a quirk of C++ language?? 或者我必须接受这个只是C ++语言的怪癖这一事实?

You don't have to use new . 您不必使用new You can create an array of Particle s as you suggested yourself: 您可以按照自己的建议创建一个Particle数组:

Particle myParticles[100];

The thing is, it will be default-constructed as you cannot specify (x,y) parameters which are only available at runtime. 问题是,它将是默认构造的,因为您不能指定仅在运行时可用的(x,y)参数。 So you will have to provide means to specify this information after the construction of a Particle , for example like this: 因此,您必须提供在构建Particle后指定此信息的方法,例如:

for( int i = 0; i < 100; i++ )
{   
    myParticles[i].SetCoords(x,y);          //x and y are randomized for each loop
}

This requires both default constructor for Particle and a method like SetCoords to configure the instance after construction. 这需要Particle默认构造函数和SetCoords类的方法在构造之后配置实例。 So it might not be an option if the code for Particle is beyond your control. 因此,如果Particle的代码超出您的控制范围,那么它可能不是一个选项。

But I would really consider using vector as it's a very convenient and useful thing. 但我真的会考虑使用vector因为它是一个非常方便和有用的东西。 It will be quite efficient as it uses very little number of dynamic allocations if programmed correctly. 如果正确编程,它将使用非常少量的动态分配,这将非常有效。 For example: 例如:

vector<Particle> myParticles;

myParticles.reserve(100);
for( int i = 0; i < 100; i++ )
{   
    myParticles.push_back(Particle(x,y));          //x and y are randomized for each loop
}

This should use just a single allocation. 这应该只使用一次分配。 This assumes that Particle is fairly lightweight to be copied by a copy constructor. 这假定Particle相当轻量级,可以由复制构造函数复制。

why do I need the use new here, because i already know beforehand how much memory i need? 为什么我需要在这里使用new,因为我事先已经知道我需要多少内存?

The reason is that probably this piece of code exists in a function. 原因是这段代码可能存在于一个函数中。 Creating an array local to the function and returning pointer/reference to it would result in Undefined behavior. 创建函数本地的数组并返回对它的指针/引用将导致未定义的行为。 So maybe the reason is to explicitly manage the lifetime of the created array elements . 所以也许原因是明确地管理所创建的数组元素的生命周期 There is no way to tell exactly unless you show more code. 除非您显示更多代码,否则无法准确说出。

Is there a code which does the same as my example code, without dynamic memory allocation? 是否存在与我的示例代码相同的代码,没有动态内存分配?

In general if given a choice, 一般来说,如果给予选择,

Particle myParticle[100];

is much better and less error prone than using dynamic memory allocations. 与使用动态内存分配相比,它更好,更不容易出错。

Good Read: 好读:
Why should C++ programmers minimize use of 'new'? 为什么C ++程序员应该尽量减少“新”的使用?

Note that while it is good to limit the use of new as much as possible, the purpose of existence of new is because it is needed for some situations where it is more suited for the behavior desired. 需要注意的是,虽然这是好事,限制使用的new尽可能地,存在的目的, new是因为它需要对某些情况下它更适合于期望的行为。 So it is more of an horses for courses. 所以它更像是一门马匹。

Particle myParticles[ 100 ];

will use the default constructor 100 time and not Particle(x,y) 将使用默认构造函数100次而不是Particle(x,y)

So, the real problem is that you have no way of passing argument to the constructor in the array. 所以,真正的问题是你无法将参数传递给数组中的构造函数。

If Particle has not default constructor Particle myParticles[ 100 ]; 如果Particle没有默认构造函数Particle myParticles[ 100 ]; will not compile 不会编译

We need more information. 我们需要更多信息。 It could be that Particle is big, but we want to sort the array. 可能是粒子很大,但我们想要对数组进行排序。 Having an array of pointers you can swap it, and this could be a lot faster than swap Particles. 有一个指针数组,你可以交换它,这可能比交换粒子快很多。 The implementation of swap of Particles could be far from trivial. 粒子交换的实现可能远非微不足道。 Finally you can pass the array calling other functions with make a copy of these pointers... Well complicate. 最后你可以传递调用其他函数的数组,并复制这些指针......这很复杂。

Being a C programmer that's how I'd roll: 作为一名C程序员,我就是这样做的:

char particle_space[sizeof(Particle) * 100];
Particle *myParticles = (Particle *) particle_space;

Then fill it the following way: 然后按以下方式填写:

for (int i = 0; i < 100; i++)
    myParticles[i] = Particle(i, i);

I don't know if using sizeof in declaration is portable or if it's gcc's extension but that worked for me. 我不知道在声明中使用sizeof是否可移植,或者它是否是gcc的扩展但是对我有用。

Particle *myParticles[ 100 ];

is array of Particle pointers, not Particles. 是粒子指针数组,而不是粒子。 And myParticles type is Particle** not just Particle*, that is why you need to allocate memory. 而myParticles类型是粒子**而不仅仅是粒子*,这就是你需要分配内存的原因。

Particle myParticles[ 100 ];

would indeed create an array of Particle and there will be no need in mem allocation. 确实会创建一个粒子数组,并且不需要在mem分配中。

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

相关问题 如何在没有动态分配的情况下创建模板对象数组 - How to create array of templated objects without dynamic allocation 对象数组动态内存分配 - Array of objects dynamic memory allocation 对象的动态内存分配 - Dynamic Memory Allocation for Objects 动态 memory 分配以使用带有 arguments c++ 的构造函数创建对象数组 - dynamic memory allocation to create array of objects using constructor with arguments c++ C ++,将临时对象添加到列表,而无需动态分配内存 - C++, adding temporary objects to a list, without dynamic memory allocation 如何在不进行动态内存分配的情况下将更多类的对象添加到向量中? - How can I add more objects of a class to a vector without doing dynamic memory allocation? 如何在C++中创建一个没有动态内存分配的链表作为模板 - How to create a linked list without dynamic memory allocation as template in c++ 如何在不使用动态内存分配的情况下创建基于指针的二叉树? - How do you create a pointer-based binary tree without using dynamic memory allocation? 在不使用动态内存分配的情况下声明可变大小的数组 - Declaring variable sized array without using dynamic memory allocation 没有动态内存分配的C ++返回数组? - C++ return array without dynamic memory allocation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM