C ++ New vs Malloc用于对象的动态内存数组 [英] C++ New vs Malloc for dynamic memory array of Objects
问题描述
我有一个类Bullet,它的构造需要几个参数。但是,我使用动态存储器阵列来存储它们。我使用C ++,所以我想符合它的标准通过使用新的运算符来分配内存。问题是,当我分配数组时,新操作符要求构造函数参数,我当时没有。我可以使用malloc获得正确的大小,然后在那里填写表单,但这不是我想使用:)任何想法。
I have a class Bullet that takes several arguments for its construction. However, I am using a dynamic memory array to store them. I am using C++ so i want to conform to it's standard by using the new operator to allocate the memory. The problem is that the new operator is asking for the constructor arguments when I'm allocating the array, which I don't have at that time. I can accomplish this using malloc to get the right size then fill in form there, but that's not what i want to use :) any ideas?
pBulletArray = (Bullet*) malloc(iBulletArraySize * sizeof(Bullet)); // Works
pBulletArray = new Bullet[iBulletArraySize]; // Requires constructor arguments
感谢。
推荐答案
不能。
如果你真的想符合C ++标准,你应该使用 std :: vector
。
And if you truly want to conform to C++ standards, you should use std::vector
.
FYI,它可能会比你想要的更昂贵。如果你能这样做, new
会调用一个构造函数。但是,由于你将修改对象后来无论如何,最初的结构是无用的。
FYI, it would probably be even more expensive than what you're trying to achieve. If you could do this, new
would call a constructor. But since you'll modify the object later on anyway, the initial construction is useless.
这篇关于C ++ New vs Malloc用于对象的动态内存数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!