c++ pointer scope

前端 未结 4 580
终归单人心
终归单人心 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 13:51

    Does text go out of scope

    Yes! It is local to the function makeItHappen() and when the function returns it goes out of scope. However the pointed to string literal "Hello, world"; has static storage duration and is stored in read only section of the memory.

    And what about the following example:

    ......
    Does the same thing occur here?

    Your second code sample leaks memory.

    SomeClass* someClass = new SomeClass();

    someClass is local to main() so when main returns it being an automatic variable gets destroyed. However the pointed to object remains in memory and there's no way to free it after the function returns. You need to explicitly write delete someClass to properly deallocate the memory.

提交回复
热议问题