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)
谢谢
以下是原始样本很麻烦的几个原因
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
然后,该方法可以根据需要填充它们.
归档时间: |
|
查看次数: |
100 次 |
最近记录: |