在 obj-c 中,我们可以按照以下方式创建向量对象:
SomeClass* example[100];
或者
int count[7000];
但是如果我们只在初始化类的时候知道向量的大小呢?(也许我们需要 example[756] 或 count[15])
SomeClass* example[100];
或者
int count[7000];
但是如果我们只在初始化类的时候知道向量的大小呢?(也许我们需要 example[756] 或 count[15])
首先,这些不是向量对象,它们是编译时数组。编译时数组的一个特性是自动内存管理;也就是说,你不用担心这些数组的分配和释放。
如果你想创建一个大小在运行时才知道的数组,你需要使用 new[]
和 delete[]
:
int size = somenumber;
int* arr = new int[size];
// use arr
arr[0] = 4;
// print the first value of arr which is 4
cout << arr[0];
关键是,当你完成这个数组后,你需要释放它:
delete[] arr;
delete
1删除由new
创建的东西,就会造成内存泄漏。但是,最好使用std::vector
,因为它可以自动管理内存。// include the header
#include <vector>
using namespace std; // so we don't have std:: everywhere
vector<int> vec; // create a vector for ints
vec.push_back(4); // add some data
vec.push_back(5);
vec.push_back(6);
// vec now holds 4, 5, and 6
cout << vec[0]; // print the first element of vec which is 4
// we can add as many elements to vec as we want without having to use any
// deallocation functions on it like delete[] or anything
// when vec goes out of scope, it will clean up after itself and you won't have any leaks
1请确保使用delete
来释放使用new
创建的指针,使用delete[]
来释放使用new[x]
创建的指针。不要混用。同样地,如果您使用std::vector
,这个问题就不需要担心了。
//file.mm
#include <vector>
-(void)function
{
std::vector<int> count;
std::vector<SomeClass*> example;
count.push_back(10); // add 10 to the array;
count.resize(20); // make count hold 20 objects
count[10] = 5; //set object at index of 10 to the value of 5
}
然后你可以这样做:
SomeClass **example = calloc(numClasses, sizeof(SomeClass *));
或者:
int *count = malloc(num_of_counts * sizeof(int));
#include <stdlib.h>
int main() {
int variable = 100;
SomeClass* example = new SomeClass[variable];
//do stuff
delete [] example; //DO NOT FORGET THIS. Better yet, use a std::vector
return 0;
}
我对Objective-C一无所知,但你的问题可能只是其中之一。
std::vector<SomeClass> my_vector(variable);
,这样我们就可以完全忘记内存管理了。 :) - Dawson
SomeClass* example[100];
并不会为您创建一个对象向量。它只是分配了一个可以容纳指向SomeClass
的指针(100)的数组。要创建一个对象,您应该使用 new 或 alloc/init。 - Mahesh