如何分配这个数组?

时间:2012-05-07 11:20:26

标签: c++

我有两种选择:

class X{
int* x;
int size = ...;
void create() { 
    x = new int[size];
    use();
    delete [] x;
}
void use() {//use array}
};

或:

class X{
int size = ...;
void create(){ 
    int x[size];
    use(x);
}
void use(int arg[]) {//use arg}
}; 

哪个更好?

2 个答案:

答案 0 :(得分:8)

选项3更好,使用std::vector

class X{
    std::vector<int> x;
    int size; // = ...; <-- the "=" part is illegal in C++03
    void create() { 
        x.resize(size);
        use();
    } 
};

此外,您的第二个代码段是非法的,C ++不支持VLA。

答案 1 :(得分:2)

第二种选择不起作用,因为尺寸不是一个恒定值。

第一种选择错过了析构函数,在那里应该执行释放(delete[] x)。

我建议使用第三种方法:对x使用std::vector<int>类。您不需要显式析构函数来释放内存,使用它通常比C样式数组更安全。