当 reset() 被unique_ptr调用两次时会发生什么?

What happens when reset() is called by a unique_ptr twice?

本文关键字:两次 什么 调用 reset unique ptr      更新时间:2023-10-16

我有以下程序,我在其中调用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(( 的参考:

  1. 保存当前指针的副本old_ptr = current_ptr
  2. 用参数current_ptr = ptr覆盖当前指针
  3. 如果旧指针不为空,则删除以前托管的对象if(old_ptr) get_deleter()(old_ptr)

因此,在unique_ptr上第二次调用reset()没有任何作用,因为旧指针是空的。新指针(也为空(与旧指针相同。