我有这种方法:
vector<float> MyObject::getResults(int n = 1000)
{
vector<float> results(n, 0);
// do some stuff
return results;
}
Run Code Online (Sandbox Code Playgroud)
当然,这并没有优化,我想返回该向量的引用,但是我不能简单地这样做:
const vector<float>& MyObject::getResults(int n = 1000)
{
vector<float> results(n, 0);
// do some stuff
return results;
}
Run Code Online (Sandbox Code Playgroud)
这是行不通的,向量将在方法结束时销毁,因为它是局部变量。
因此,我发现解决此问题的唯一方法是在MyObject中创建一个私有向量,并返回对此向量的引用:
const vector<float>& MyObject::getResults(int n = 1000)
{
this->results.clear();
this->results.resize(n, 0);
// do some stuff
return results;
}
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?您还有其他解决方案可以提出吗?