我对 C++ 和智能指针很陌生,尤其是 unique_ptr 的行为。下面是我正在试验的一段代码:
unique_ptr<int> u1 = make_unique<int>(2);
unique_ptr<int> u2 = make_unique<int>();
u2.reset(u1.get());
Run Code Online (Sandbox Code Playgroud)
根据定义,unique_ptr 是一种智能指针,它不与其他智能指针共享它所指向的对象的所有权。但是,为什么上面的代码没有返回错误呢?事实上,如果我尝试打印 u1 和 u2 的值,结果它们确实指向相同的内存地址:
cout<<u1.get()<<endl;
cout<<u2.get()<<endl;
Run Code Online (Sandbox Code Playgroud)
在控制台上显示这些:
0x55800839ceb0
0x55800839ceb0
free(): double free detected in tcache 2 // finally the error appears at the end of the program's execution
Run Code Online (Sandbox Code Playgroud)
但如果我说:
cout<<(*u1)<<endl;
(*u1)=5;
cout<<(*u2)<<endl;
Run Code Online (Sandbox Code Playgroud)
更改不会影响 (*u2),就好像它们位于不同的内存地址中一样。
任何帮助,将不胜感激!感谢您的时间!