最好如何分配此数组

  • 本文关键字:分配 数组 何分配 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}
}; 

哪个更好?

选项 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。

第二种选择不起作用,因为大小不是一个常量值。

第一种选择缺少析构函数,其中应该执行释放(delete[] x)。

我建议第三种选择:对x使用std::vector<int>类。不需要显式析构函数来解除分配内存,并且通常比 C 样式数组更安全。

最新更新