我很难适应 C++ 处理动态和自动内存的方式。
我的问题:
指向自动分配实例的指针是否可以保留该实例解除分配,即使实例化范围已离开?
<罢工>在this帖子我读到所有指向 dealloc 内存的指针都是无效的。
但这家伙是在谈论手动解除分配还是自动解除分配后的行为?
这是一个例子:
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;
}
最佳答案
automatic memory: When is it deallocated?
当变量超出范围时。或者在自动成员变量的情况下,当拥有对象被销毁时。
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?
不,它不能。指针只是一直指向现在无效的内存。无论对象的销毁方式如何(自动、动态或静态释放),指向已销毁对象的指针和引用始终无效。
在您的示例中,root
在 createSomeScope
的末尾被释放,并且您在 UiTreeRecord::attachParent
中分配的指针变得无效。
关于C++自动内存: When is it deallocated?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34484996/