C++,不带 <vector> 的对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2493431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++, array of objects without <vector>
提问by osgx
I want to create in C++ an array of Objects without using STL.
我想在 C++ 中创建一个不使用 STL 的对象数组。
How can I do this?
我怎样才能做到这一点?
How could I create array of Object2, which has no argumentless constructor (default constructor)?
如何创建没有无参数构造函数(默认构造函数)的 Object2 数组?
回答by sharptooth
If the type in question has an no arguments constructor, use new[]
:
如果有问题的类型具有无参数构造函数,请使用new[]
:
Object2* newArray = new Object2[numberOfObjects];
don't forget to call delete[]
when you no longer need the array:
delete[]
当您不再需要数组时,不要忘记调用:
delete[] newArray;
If it doesn't have such a constructor use operator new
to allocate memory, then call constructors in-place:
如果没有这样的构造函数用于operator new
分配内存,则就地调用构造函数:
//do for each object
::new( addressOfObject ) Object2( parameters );
Again, don't forget to deallocate the array when you no longer need it.
同样,不要忘记在不再需要数组时释放它。
回答by Kirill V. Lyadvinsky
// allocate memory
Object2* objArray = static_cast<Object2*>( ::operator new ( sizeof Object2 * NUM_OF_OBJS ) );
// invoke constuctors
for ( size_t i = 0; i < NUM_OF_OBJS; i++ )
new (&objArray[i]) Object2( /* initializers */ );
// ... do some work
// invoke destructors
for ( size_t i = 0; i < NUM_OF_OBJS; i++ )
objArray[i].~Object2();
// deallocate memory
::operator delete ( objArray );
回答by mukeshkumar
Assuming that your class is Base and you have a one argument constructor
假设您的类是 Base 并且您有一个单参数构造函数
Base arr[3] = {Base(0), Base(1), Base(2)} ;
回答by Raul Agrait
Object2 *myArray[42];
for (int i = 0; i < 42; i++)
{
myArray[i] = new Object2(param1, param2, ...);
}
Later on you will have to walk through the array and deallocate each member individually:
稍后您将不得不遍历数组并单独释放每个成员:
for (int j = 0; j < 42; j++)
{
delete myArray[j];
}
回答by Jeremy Bell
Use an array of pointers to Object2:
使用指向 Object2 的指针数组:
std::tr1::shared_ptr<Object2>* newArray = new shared_ptr<Object2>[numberOfObjects];
for(int i = 0; i < numberOfObjects; i++)
{
newArray[i] = shared_ptr<Object2>(new Object2(params));
}
Or, alternatively, without the use of shared_ptr:
或者,不使用 shared_ptr:
Object2** newArray = new Object2*[numberOfObjects];
for(int i = 0; i < numberOfObjects; i++)
{
newArray[i] = new Object2(params);
}
回答by Jeremy Bell
You can do what std::vector
does and create a block of raw memory. You then construct your objects which don't have a default constructor in that memory using placement new, as they are required. But of course, if you do that you might as well have used std::vector
in the first place.
您可以执行该std::vector
操作并创建原始内存块。然后,根据需要,使用placement new 构造在该内存中没有默认构造函数的对象。但是,当然,如果您这样做,您最好一开始就使用std::vector
它。
回答by David Thornley
The obvious question is why you don't want to use the STL.
显而易见的问题是为什么您不想使用 STL。
Assuming you have a reason, you would create an array of objects with something like Obj * op = new Obj[4];
. Just remember to get rid of it with delete [] op;
.
假设您有理由,您将创建一个对象数组,其中包含类似Obj * op = new Obj[4];
. 只记得用 摆脱它delete [] op;
。
You can't do that with an object with no constructor that doesn't take arguments. In that case, I think the best you could do is allocate some memory and use placement new. It isn't as straightforward as the other methods.
对于没有不带参数的构造函数的对象,您不能这样做。在这种情况下,我认为你能做的最好的事情就是分配一些内存并使用新的布局。它不像其他方法那么简单。
回答by Bj?rn Pollex
If no default constructor is available, you will need an array of pointers, and then loop over that array to initialize each of the pointers.
如果没有可用的默认构造函数,您将需要一个指针数组,然后循环遍历该数组以初始化每个指针。
回答by CB Bailey
If you genuinely need an array (contiguous sequence of objects) of a non-default constructible type and for some reason you cannoy user std::vector
(!?) then you have to use a raw allocation function and placement new.
如果你真的需要一个非默认可构造类型的数组(连续的对象序列),并且由于某种原因你会惹恼用户std::vector
(!?),那么你必须使用原始分配函数和放置新的。
This is very hard to do reliably; this should help to show why. This snippet includes some defence against exceptions but is more than likely not robust against all failures.
这很难可靠地做到;这应该有助于说明原因。此代码段包括一些针对异常的防御,但很可能无法抵御所有故障。
const size_t required_count = 100; //e.g.
// cast to pointer of required type needed for pointer arithmetic
Object2* objarray = static_cast<Object2*>(operator new(required_count * sizeof(Object2)));
size_t construction_count = 0;
try
{
while (construction_count < required_count)
{
// params could change with index.
new (static_cast<void*>(objarray + construction_count)) Object2(param1, param2);
++construction_count;
}
}
catch (...)
{
while (construction_count-- != 0)
{
try
{
(&objarray[construction_count])->~Object2();
}
catch (...)
{
// not a lot we can do here, log but don't re-throw.
}
}
operator delete(objarray);
throw;
}
// Now objarray has been allocated and pointer to an array of required_count Object2
// It cannot be de-allocated via delete[] or delete; you must loop through
// calling destructors and then call operator delete on the buffer.