Thursday 10 January 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...