Scope/Stack/Memory Question

I wrote a simple program here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <vector>
#include <string>

class Person{
public:
    std::string name;
    ~Person() { std::cout << "Destroying person\n"; }
};

int main(){
    std::vector<Person*> people;

    if(true){
        Person me;
        me.name = "Eric";

        people.push_back(&me);
        std::cout << "The address of me is: " << &me << std::endl;
    } // me is destroyed and goes out of scope; it's released from the stack

    std::cout << "The first element points to address: " << people[0] << std::endl;
    std::cout << "The first name is: " << people[0]->name << std::endl;

    return 0;
}


I have several questions about why it works. In my if statement, I'm creating a local instance of Person, called me. Since it's allocated on the stack, from my understanding it is destroyed when it goes out of scope. The destructor shows output as expected.

However, when I print out the contents from the vector, the name still prints out clearly. This is contrary to what I'd expect because the memory was just released/destroyed; shouldn't this cause undefined behavior? Why does it still print the name even though the destructor was already called on that object?
Last edited on
Undefined behavior means there are no guarantees about what will happen. One possible outcome is that it behaves as if the object was still alive.
Last edited on
As Peter87 said, it is undefined behavior. An examination of what happening will explain why it "appears" to work.

Line 15: The stack is extended by the size of Person and Person's constructor is called. name's constructor is also called. Note that in most implementations, string will only allocate additional memory from the heap if the string is larger than 15 bytes. In your case, "Eric" is 4 bytes and is stored directly in the std::string.

Line 20: Person's destructor is called. std::string's destructor is called. Since "Eric" was never allocated on the heap, it still exists at the same place on the stack. The stack marker is decremented by the size of Person. This does not change memory at all. people[0] still points to where me was on the stack. If something else were allocated on the stack at line 21, a portion or all of me would be overwritten.

Thans for your responds cause I have a similar problem and I can't get over it!
Thank you for clarifying.
Topic archived. No new replies allowed.