I am trying to learn C ++, and from my understanding, if a variable goes out of scope, it is destroyed and its memory is redistributed. If I have a class and it creates a variable, should this variable not be destroyed after the method is called? For example:
class TestClass {
public:
struct Pair{
std::string name;
int value;
};
void addPair() {
Pair x = Pair{ std::string{ "Test Object " }, counter++ };
pairs.push_back(x);
}
void printPairs() {
for (int i = 0; i < pairs.size(); i++) {
std::cout << "pair { " << pairs[i].name << " : " << pairs[i].value << " } " << std::endl;
}
}
void removePair() {
pairs.pop_back();
}
private:
int counter;
std::vector<Pair> pairs;
};
But when I tried addPair()
, then printPairs()
, then removePair()
it works great. Why does he not give an error, talking about incorrect access to the memory cell?
source
share