从堆栈分配的原始指针构造智能指针
Constructing smart pointer from stack allocated raw pointer
有人可以启发我这里发生的事情吗?
int* stackint = new int(5);
{
std::unique_ptr<int> myInt(stackint);
*myInt = 8;
}
std::cout << *stackint; // 0
这里到底发生了什么?我理解智能指针,当你用新的或make_unique构造它们时,当你将堆栈指针传递给它们的构造函数时会发生什么?
下面是一个注释:
int* stackint = new int(5); // an int is allocated on the heap, and set to 5
{
std::unique_ptr<int> myInt(stackint); // myInt takes ownership of the allocation
*myInt = 8; // The value 5 is overwritten by 8
} // myInt goes out of scope, its destructor deletes the heap allocation
std::cout << *stackint; // undefined behavior: attempt to read from already-freed memory
代码具有未定义的行为。
std::unique_ptr<int> myInt(stackint);
构造一个拥有stackint
指向的对象unique_ptr
。指针本身具有的存储类型无关紧要,只有其值传递给构造函数,并且该值指向通过调用new
创建的int
对象,这意味着该int
对象具有动态存储持续时间。
然后myInt
的析构函数在块的末尾被调用(}
(,并delete
它管理并且stackint
仍然指向的int
对象,这意味着stackint
的值现在是一个无效的指针值。
然后,使用*stackint
取消引用该无效指针值,这会导致未定义的行为。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 优先顺序:智能指针和类析构函数
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 智能指针作为无序映射键,并通过引用进行比较
- 智能指针概念所有权和寿命
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 尝试使用智能指针时引发异常
- 我可以制作指向智能指针的智能指针吗?
- 通过智能指针和转换对基本模板参数进行模板推导
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 从堆栈分配的原始指针构造智能指针
- 初始化指向类实例的智能指针并访问其方法
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 编译器不会使用 -std=c++11 编译智能指针
- 具有智能指针的多态性
- C++:矢量分配器行为、内存分配和智能指针
- 通过简单的包装指针C++智能指针性能和差异
- 矢量中的自动指针(智能)
- Std::vector的对象/指针/智能指针传递对象(总线错误:10)