动态分配数组(向量实现的动态大小)
在 obj-c 中,我们可以按如下方式创建向量对象:
SomeClass* example[100];
或者
int count[7000];
但是如果我们仅在初始化类时才知道向量的大小怎么办? (也许我们需要 example[756] 或 count[15])
In the obj-c, we can create vector objects as follows:
SomeClass* example[100];
or
int count[7000];
But what if we know the size of the vector only at the time init the class?
(Maybe we need example[756] or count[15])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,这些不是向量对象,它们是编译时数组。编译时数组的特点之一是自动内存管理;也就是说,您不必担心这些数组的分配和释放。
运行时才知道其大小的数组,则需要使用
new[]
和delete[]
:如果您想创建一个直到 你已经完成了这个数组,你必须释放它:
如果你忘记用相应的
delete
释放由new
创建的东西1,您将创建一个内存泄漏。不过,您可能最好使用
std::vector
,因为它会自动为您管理内存:1 确保对您希望使用的指针使用
delete
在使用new[x]
创建的指针上使用new
和delete[]
创建。 不要混合搭配它们。同样,如果您使用 std::vector,则不必担心这一点。First of all, those aren't vector objects, they're compile-time arrays. One of the features of compile time arrays is automatic memory management; that is, you don't have to worry about allocation and deallocation of these arrays.
If you want to create an array whose size you don't know until runtime, you'll need to use
new[]
anddelete[]
:The catch is that after you're done with this array, you have to deallocate it:
If you forget to deallocate something created by
new
with a correspondingdelete
1, you'll create a memory leak.You are probably better off using
std::vector
though because it manages memory for you automatically:1 Make sure you use
delete
on pointers that you created withnew
anddelete[]
on pointers you make withnew[x]
. Do not mix and match them. Again, if you usestd::vector
, you don't have to worry about this.为什么不只使用 std::vector
Why not just use an std::vector
然后你做类似的事情:
或:
请注意,你应该:
Then you do something like:
or:
Note that you should:
C++ 无法创建可变大小的全局/局部数组,只能创建堆上的动态数组。
我对 Objective-C 一无所知,但你的问题可能只是其中之一。
C++ cannot make global/local arrays of a variable size, only dynamic arrays on the heap.
I don't know anything about objective-C, but your question is probably only one or the other.