为什么不能将智能指针声明为通常的指针方式

问题描述 投票:0回答:1

我已经阅读了有关初始化唯一指针here的文档。我试图以相同的方式声明唯一指针(see unique_ptr<int> temp1 {&h},尽管我只是在试验中,但在文档中没有看到这种声明),但我声明了非智能指针。进行此实验的想法是查看std::unique_ptr::get()方法的工作原理。这是代码:

#include<iostream>
#include<stdio.h>
#include<memory>

using namespace std  ;
int main(){

int h {100};
unique_ptr<int> temp1 {&h};

cout<<"temp1.get() :"<<temp1.get()<<endl;
cout<< "&h : "<<&h<<endl;
cout<<"*temp : "<<*temp1<<endl;
    return 0 ; 
}

代码编译,我得到以下输出:

temp1.get() :0x7ffd4322c5cc
&h : 0x7ffd4322c5cc
*temp : 100
/home/abhishek/.codelite/tmp/abhishek/codelite-exec.sh: line 3:  7889 Segmentation fault      (core dumped) ${command}
Hit any key to continue...

我可以看到std::unique_ptr::get()返回托管对象的地址,该地址与&h相同。这里的错误是什么?尽管已经讨论了向智能指针分配地址here。它不能回答我的问题。

c++ c++14 smart-pointers
1个回答
0
投票

感谢@KamilCuk给出了直觉。智能指针无法像普通指针那样进行初始化,因为使用普通指针可以选择“不删除”内存。默认情况下,智能指针会在超出范围时删除内存。现在,只有在通过new运算符将其分配到堆上时,才可以删除内存。有关此的更多信息是here

© www.soinside.com 2019 - 2024. All rights reserved.