在子函数中实例化的类大小,即这是使用new的好时机吗?

use*_*670 1 c++ pointers new-operator

我想创建一个数据向量,但我想设置它的大小并在子函数中填充它的元素.这是使用新运营商的合适时机吗?有没有更好的方法呢?这似乎是一个合适的时间,但我犹豫不决,因为为什么C++程序员应该尽量减少"新"的使用?

int main()
{
    vector<double> *array1;
    vector<double> *array2;
    OtherArgs otherArgs;
    FillArrays(array1,array2,otherArgs);
    //Do other stuff 
    delete array1;
    delete array2;
}

void FillArrays(vector<double> *&array1, vector<double> *&array2, OtherArgs &otherArgs)
{
    int size=GetSize(otherArgs);
    array1 = new vector<double>(size);
    array2 = new vector<double>(size);
    //Other code to fill the arrays
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Jar*_*Par 7

以下是原始样本很麻烦的几个原因

  • 代码在异常时泄漏内存,因为delete调用不受保护
  • 如果FillArrays传递非NULL vectory<double>值,它将泄漏内存,因为它没有删除以前的值.delete即使它想要它也无法可靠地调用,因为该值可能已经被堆栈分配.

最简单的方法是在堆栈上声明值并通过引用传递它们.

int main()
{
    vector<double> array1;
    vector<double> array2;
    OtherArgs otherArgs;
    FillArrays(array1,array2,otherArgs);
    //Do other stuff 
}

void FillArrays(vector<double> &array1, vector<double> &array2, OtherArgs &otherArgs)
{
    int size=GetSize(otherArgs);
    //Other code to fill the arrays
}
Run Code Online (Sandbox Code Playgroud)

vector<T>当以这种方式声明时,它将自己初始化为空列表.FillArrays然后,该方法可以根据需要填充它们.

  • +1 - 这样你仍然可以做`array1 = vector <double>(size);`或类似的. (3认同)