struct Word {
string wordName; //loses its value
vector<string> contents; //irrelevant for the question
int numContents = 0; //maintains its value
};
vector<Word*> wordMsgs;
int main()
{
vector<string> result;
result.push_back("wordName");
result.push_back("shouldEnterIf");
Word curr;
//New Word
if (result[1] != "") {
Word w;
w.numContents = 10; //just a testing #, suppose to represent size of vector
wordMsgs.push_back(&w);
w.wordName = result[0]; //name of Word
//here w.wordName and (*wordMsgs[0]).wordName display the same string; result[0]
curr = w;
}
//here curr.wordName displays result[0] but (*wordMsgs[0]).wordName doesn't. However, (*wordMsgs[0]).numContents returns 10 as expected
}
}
So I have a vector of struct references, assuming the push_back() method for vectors only pushes a copy to the end of the vector. I create an instance of my Word struct and put that reference into my vector, wordMsgs. I then edit the struct it is pointing too and then my string variable is lost upon leaving the if statement! However, my int variable never loses its value. I don't understand because I used pointers (and I'm in C++ so I thought strings were a-okay) and I wouldn't think this is a local variable issue...