Reputation: 602
I have a member function which fills a vector with objects:
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)
}
No matter how many times the while loop is run, the function always returns an empty vector. This implies that my while loop does nothing. How is this possible?
EDIT: After playing with the code for a while, I noticed that the issue was returning by reference. But why did returning by reference cause this issue?
Upvotes: 1
Views: 343
Reputation: 15824
You are returning the reference of a local variable, that is the issue. Th scope of the local variable optData
is only inside the function and as soon you reach the last brace of your function, system will call the destructor of it.
So correction needed to change it to return by value and NRVO will be taken care rest of it. So change your function as follows
std::vector<OptionData> OptionData::createMeshExpiry(const double T_start, const double T_end, double T_increment)
{
//....
}
Upvotes: 4