Thursday, January 10, 2019

C++ automatic memory: When is it deallocated?



I am having a hard time getting used to the way C++ handles dynamic and automatic memeory.
My question:





  • Can a pointer, that points to an automatic allocated instance, keep that instance from deallocation even after the scope of the instanciation has been left?
    In this post I read that all pointers pointing to dealloc memory are invalid.
    But is this guy talking about the behaviour after a manual dealloc or an automatic dealloc?




This is an example:



int main(){
UiTreeRecord child = UiTreeRecord::UiTreeRecord();
createSomeScope(child);

//Does child still have a valid parent?
//Or does parent point to a piece of memory that has been deallocated?
}

void createSomeScope(const UiTreeRecord& child){
UiTreeRecord root = UiTreeRecord::UiTreeRecord();
child.attachParent(root);
}

void UiTreeRecord::attachParent(UiTreeRecord& newParent) {

if(parent != nullptr) {
detachParent();
}
parent = &newParent;
}

Answer




automatic memory: When is it deallocated?





When the variable goes out of scope. Or in the case of automatic member variable, when the owning object is destroyed.




Can a pointer, that points to an automatic allocated instance, keep that instance from deallocation even after the scope of the instanciation has been left?




No, it can't. The pointer simply keeps pointing at the memory that is now invalid. Pointers and references to a destroyed object always become invalid regardless of the way the object was destroyed - be it automatic, dynamic or static deallocation.



In your example, root is deallocated at the end of createSomeScope and the pointer that you assigned in UiTreeRecord::attachParent becomes invalid.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...