When a pointer is created in scope, what happens to the pointed to variable when the pointer goes out of scope?

前端 未结 4 1244
猫巷女王i
猫巷女王i 2021-01-02 16:14

The title says it all.

I found an old question that is essentially the same, but I needed a tiny bit further clarification.

In this question the accepted an

4条回答
  •  情歌与酒
    2021-01-02 16:22

    Your example is, unfortunately, insufficient to address the full picture.

    First of all, some simple adhoc vocabulary and explanations: a memory cell is a (typed in C++) zone of memory with a given size, it contains a value. Several memory cells may contain identical values, it does not matter.

    There are 3 types of memory cells that you should be considering:

    • "Hello, World!": this memory cell has static storage duration, it exists throughout the duration of the program
    • void foo(int a); and void foo() { int a = 5; }: the memory cell a, in both cases, has automatic storage duration, it will disappear automatically once the function foo returns
    • void foo() { int* a = new 5; }: an anonymous memory cell is created "somewhere" to store the value 5, and a memory cell a with automatic storage duration is created to store the address of the anonymous one

    So, what happens when a pointer goes out of scope (disappear) ?

    Well, just that. The pointer disappear. Most specifically, nothing special happens to the memory cell it was pointing to.

    void foo(int a) {
        int* pointer = &a;
    } // pointer disappears, `a` still exists briefly
    
    void foo() {
        int* pointer = 0;
        {
            int a;
            pointer = &a;
        } // a disappears, pointer's value does not change...
    } // pointer disappears
    

    Indeed, in C and C++:

    • you can retain the addresses of objects that no longer exists => dangling reference
    • you can lose all addresses to an existing object => memory leak

    So what happens when text in char const* text = "Hello, world"; goes out of scope ?

    Nothing.

提交回复
热议问题