I've encountered this piece of existing code, and being still new to C++, I don't understand why storing a local variable into a vector makes it still accessible later.
Here's the simplified flow of the code, where BackendCall is some class defined earlier:
void SaveBackendCall(BackendCall* backend_call,
vector<BackendCall>* logged_calls) {
logged_calls->push_back(*backend_call);
}
void AddNewCall(vector<BackendCall>* logged_calls) {
BackendCall backend_call; // The local variable in question.
SaveBackendCall(&backend_call, logged_calls);
}
vector<BackendCall> logged_calls;
AddNewCall(&logged_calls);
for (auto i = logged_calls->begin(); i != logged_calls->end(); ++i) {
i->access_stuff(); // This still works?
}
Wouldn't the local variable backend_call in AddNewCall() be destroyed after the function returns? Then I don't understand what is actually stored in logged_calls.
Would it make sense to convert the vector of BackendCall objects into a vector of unique_ptrs?