Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Scope of Variables Created in a Class Method

I'm trying to learn C++, and from my understanding if a variable goes out of scope then it is destroyed and its memory is reallocated. If I have a class and it's method creates a variable, shouldn't that variable be destroyed after the method call? 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 fine. Why doesn't it throw an error saying invalid access to memory location?

like image 301
Doe Avatar asked Dec 11 '22 20:12

Doe


2 Answers

First, access to variables out of scope is undefined behavior. The program might throw an error but it might even work well. So there's no guarantee an error will be raised.

Second, std::vector::push_back makes a copy of its arguments. So nothing to worry about when passing local variables to it.

like image 24
cadaniluk Avatar answered Dec 13 '22 11:12

cadaniluk


You said:

from my understanding if a variable goes out of scope then it is destroyed and its memory is reallocated.

That is correct. "reallocated" is not correct word I would use. I would phrase that as: The memory used by the object is available to be used by other objects.

And then you asked:

If I have a class and it's method creates a variable, shouldn't that variable be destroyed after the method call?

That is correct.

However, your situation is different.

When you use:

pairs.push_back(x);

a copy of x is placed in pairs. The copy continues to live in pairs after the function returns. Hence, printPairs() and removePair() work just fine.

like image 103
R Sahu Avatar answered Dec 13 '22 09:12

R Sahu