@giuliomoro Alright, I think I'm on the verge of getting this working. I did what you outline above, the only difference being I kept the return value of getCurrentSong
as nlohmann::json*
because it's an object. Also, currentSongId
is another private int added to the header along with a simple setter.
Everything compiles but then I get a runtime error the first time I try call getCurrentSong
. When I parse the JSON on startup I'm setting the private state variable like so:
void SaveState::loadSaveState() {
std::ifstream f(kStateJsonFilepath);
nlohmann::json tempState = json::parse(f);
state = &tempState;
int currentSongId = state->value(kCurrentSongId, kIdNotFound);
rt_printf("CURRENT SONG ID: %d\n", currentSongId);
if (currentSongId != kIdNotFound) {
setCurrentSongId(currentSongId);
}
rt_printf("state: %s\n", state->dump(-1).c_str());
}
At the end of that same function, I've verified that the json has been properly parsed via:
rt_printf("state: %s\n", state->dump(-1).c_str());
which looks exactly as I'd expect.
However, when I call getCurrentSong
and try to run the same print statement from there, I'm getting mixed bad results:
nlohmann::json* SaveState::getCurrentSong() {
rt_printf("state in getCurrentSong: %s\n", state->dump(-1).c_str());
for(auto &song : (*state)[kSongs]) {
int songId = song[kSongId];
if (songId == currentSongId) {
return &song;
}
}
return &kIdNotFound;
}
The first time it's called I get
rt_printf("state in getCurrentSong: %s\n", state->dump(-1).c_str());
// null
The second time I get
rt_printf("state in getCurrentSong: %s\n", state->dump(-1).c_str());
// {"songs": null}
There are no places in which that private state
variable are being set or modified except for in that initial load function where I am successfully setting/reading from/printing out the dereferenced variable. The getCurrentSong
function works perfectly when the state
variable is not a pointer. The only change I made to the loadSaveState
function was to first load the parsed JSON data into a tempState
variable before assigning the class instance's state
variable to the pointer. I only did this because trying to do it directly like so
state = &(json::parse(f));
produced an error: `Taking the address of a temporary object of type 'nlohmann::json...etc'
Am I doing anything obviously wrong here? It seems to me like maybe that tempState
variable is getting discarded at the end of the function call and so when I try to read the state variable later it is null? Although I don't see why I'd get two different results when trying to parse the state. I'm not sure I can see the way around this without declaring another private variable in the header that is not a pointer. Thoughts?