c++ pointer scope

前端 未结 4 579
终归单人心
终归单人心 2020-12-25 13:47

What happens when you have the following code:

void makeItHappen()
{
    char* text = \"Hello, world\";
}

Does text go out of

4条回答
  •  青春惊慌失措
    2020-12-25 14:12

     char* text = "Hello, world";
    

    Here an automatic variable (a pointer) is created on the stack and set to point to a value in constant memory, which means:

    • the string literal in "" exists through the whole program execution.
    • you are not responsible for "allocating" or "freeing" it
    • you may not change it. If you want to change it, then you have to allocate some "non-constant memory" and copy it there.

    When the pointer goes out of scope, the memory pointer itself (4 bytes) is freed, and the string is still in the same place - constant memory.

    For the latter:

    SomeClass* someClass = new SomeClass();
    

    Then someClass pointer will also be freed when it goes out of scope (since the pointer itself is on the stack too, just in the first example)... but not the object!

    The keyword new basically means that you allocate some memory for the object on free store - and you're responsible for calling delete sometime in order to release that memory.

提交回复
热议问题