C ++ - The scope of variables created in a class method

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() {
    //should be deleted after push_back is called?
    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?

+4
source share
2 answers

-, - undefined. , . , , .

-, std::vector::push_back . .

+5

:

, , .

. "reallocated" - , . : , , .

:

, , ?

.

.

:

pairs.push_back(x);

x pairs. pairs . , printPairs() removePair() .

+8

Source: https://habr.com/ru/post/1612329/


All Articles