我有一个成员函数,它用对象填充 vector :

std::vector<OptionData>& OptionData::createMeshExpiry(const double T_start, const double T_end, double T_increment)
{ // Ouput a vector filled with option data spread
    std::vector<OptionData> optData;
    m_T = T_start; // intialize to first value
    while(m_T <= T_end)
    {
        optData.push_back(*this); // push the current instance onto the vector
        m_T += T_increment; // increment expiry time
    }
    return optData; // return by reference to enable a cascading effect (if needed to change more than one var)
}

无论while循环运行了多少次,该函数始终返回一个空 vector 。这意味着我的while循环什么也不做。这怎么可能?

编辑:在玩了一段时间的代码后,我注意到该问题是通过引用返回。但是,为什么通过引用返回会导致此问题呢?

最佳答案

您正在返回局部变量的引用,这就是问题所在。局部变量optData的作用域仅在函数内部,一旦您到达函数的最后一个括号,系统就会调用它的析构函数。

因此,需要进行更正以将其更改为按值返回,并且NRVO会在剩下的时间内得到处理。因此,如下更改功能

std::vector<OptionData> OptionData::createMeshExpiry(const double T_start, const double T_end, double T_increment)
{
 //....
}

10-08 08:28
查看更多