简体   繁体   中英

C++ Pointer in function Scope/Destruction

Please forgive this question because it is likely along the lines of being elementary. Also, I have extensively googled this, but all I found were examples using implementations that quite obviously result in a memory leak.

Take note of the following pseudo code:

void myArbitraryFunc(){
...
// Create Pointer to parent class
MyParentClass* parent = (MyParentClass*)this.getParent();
parent->doSomething(someData);
...
}// Is parent destroyed here?

By destroyed I don't meam the parent class, I mean the pointer "parent", which I declared in the function body. It is destroyed when it falls out of scope, correct? If yes, why? And how would I create a duplicate of the class pointer without it being tied to the original parent?

The pointer parent is destroyed. What it points to, however, is not destroyed.

The pointer itself is just a variable on the stack, and goes away when the stack unwinds, when the current scope ends. It is conceptually no different from this code:

void myArbitraryFunc() {
    ...
    int parent = 42;
    ....
} // parent goes away

The way to think about it is that a pointer is just a number, that number being the memory address of the object pointed to.

Now in your example, we presume that the MyParentClass object itself was created by something else, and is owned by something else, so myArbitraryFunc is not responsible for deleting it.

A pointer is really just a number, and "address" of the object. Imagine memory as a giant set of boxes, with a number. You ask the system to create an object, and it does so, and tells you that the object is in box 42. Obviously writing copies of '42' isn't doing anything to the object itself. It's just making lots of copies of the address.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM