gpt4 book ai didi

c++ - 通过动态内存管理防止自动变量销毁

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:08 25 4
gpt4 key购买 nike

据我了解,动态内存分配可用于控制对象的生命周期。当我“新建”一个对象时,它会保留在内存中的堆上,直到我删除它。

现在,有时候事情并没有那么简单。在一种情况下就是这种情况,在这种情况下,我想保留某些内存块,直到我释放它,以防止破坏该内存块中的数据。例如,我想将指向分配在堆栈上的对象的指针插入到 vector 中。只要指向对象的指针在该 vector 中,指针指向的对象就不能被销毁。这是出于安全原因。如何实现这一点,使用动态内存分配保留一 block 内存?

最佳答案

做你想做的最简单的方法是使用 smart pointers

您可以使用:

"Smart pointers are objects which store pointers to dynamically allocated (heap) objects. They behave much like built-in C++ pointers except that they automatically delete the object pointed to at the appropriate time. Smart pointers are particularly useful in the face of exceptions as they ensure proper destruction of dynamically allocated objects. They can also be used to keep track of dynamically allocated objects shared by multiple owners.

Conceptually, smart pointers are seen as owning the object pointed to, and thus responsible for deletion of the object when it is no longer needed."

std::unique_ptr is a smart pointer that retains sole ownership of an object through a pointer and destroys that object when the unique_ptr goes out of scope. No two unique_ptr instances can manage the same object.

std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object.

关于c++ - 通过动态内存管理防止自动变量销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16293656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com