当 reset() 被unique_ptr调用两次时会发生什么?
What happens when reset() is called by a unique_ptr twice?
我有以下程序,我在其中调用mc.reset((两次。我以为这会给我一个错误,但这没有错误。
#include <iostream>
#include <csignal>
#include <memory> // for unique pointer
using namespace std;
std::unique_ptr<int> mc;
void signal_handler( int signal_num ) {
cout << "The interrupt signal is (" << signal_num << "). n";
mc.reset();
mc.reset();
// terminate program
exit(signal_num);
}
int main () {
mc.reset (new int);
*mc = 5;
// Press Control + c to raise SIGINT
signal (SIGINT, signal_handler);
while(true)
cout << "Hello..." << endl;
return 0;
}
我使用 valgrind 检查内存泄漏,但没有发现:
==5467==
==5467== HEAP SUMMARY:
==5467== in use at exit: 0 bytes in 0 blocks
==5467== total heap usage: 3 allocs, 3 frees, 73,732 bytes allocated
==5467==
==5467== All heap blocks were freed -- no leaks are possible
==5467==
==5467== For counts of detected and suppressed errors, rerun with: -v
==5467== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
调用重置时实际发生了什么?为什么我可以毫无问题地调用它两次?
参见 reset(( 的参考:
- 保存当前指针的副本
old_ptr = current_ptr
- 用参数
current_ptr = ptr
覆盖当前指针- 如果旧指针不为空,则删除以前托管的对象
if(old_ptr) get_deleter()(old_ptr)
。
因此,在unique_ptr
上第二次调用reset()
没有任何作用,因为旧指针是空的。新指针(也为空(与旧指针相同。
相关文章:
- g++的分段错误(在NaN上使用to_string两次时)
- 蛇在C++不会连续转两次
- 检查一个数组是否包含在另一个数组中,以相反的顺序,至少两次
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 我应该如何去缓解两次出现的cin?
- Realloc 两次无法在 Visual Studio 上运行
- 如果我使用同一个密钥推送用户数据两次,会发生什么
- 当 reset() 被unique_ptr调用两次时会发生什么?
- 两次商店有什么
- 两次删除链表有什么区别?
- 在C 中,当使用两次时,这意味着什么
- 有什么方法可以通过删除表达式安全地处理两次释放内存?
- 执行随机开关函数的QT方式是什么连续两次使用相同情况的方法
- 如果参数传递两次,会发生什么情况?一次按值,一次按引用?是否会修改
- C++重载运算符两次,一个返回非常量引用,另一个返回常量引用,首选项是什么
- 是什么原因导致Windows发送ID_HELP命令两次
- "!!"(否定两次)的用法是什么?
- 为什么Microsoft在他们的 winnt.h 文件中两次 typedef 声明什么构成 "double" ?
- 不知道出了什么问题 - 两次程序隔离错误
- 什么是delete指针,指针=0;表述功?它清除内存两次吗?