pointers - 在函数中声明共享指针会产生内存泄漏行为
问题描述
我一直在尝试理解智能指针,据我所知,一旦无法通过代码访问智能指针,它们就会自行销毁。
出于这个原因,我试图对此行为进行演示:
#include<iostream>
#include<memory>
using namespace std;
void shared(){
cout<<"Shared Pointer:"<<endl;
shared_ptr<int> number = make_shared<int>(50);
cout<<*number<<endl;
cout<<number<<endl;
}
int main(){
int address;
shared();
cout<<"please enter the targeted address:"<<endl;
cin>>address;
int *pointer = (int *) address;
cout<<"we found this number: "<<*pointer<<endl;
}
输出:
Shared Pointer:
50
0xf28c30
please enter the targeted address:
15895600 // I just converted the hexdecimal above to decimal number.
we found this number: 50
因此,我可以shared()
通过在控制台中手动输入其地址,从函数外部检索值 50。不应该是空数或随机数吗?如果这是正常的,那么如何制作智能指针以避免内存泄漏!?
PS:使用普通指针进行相同的测试将产生相同的结果,除非我们添加delete pointer;
(这是预期的行为)
我很欣赏有关这种特定行为的任何想法。
解决方案
为了确保内存被删除,最好用一个类测试智能指针
class Greeting {
public:
Greeting()
{
std::cout << "Hello" << std::endl;
}
~Greeting()
{
std::cout << "Bye" << std::endl;
}
};
void shared() {
shared_ptr<Greeting> var = make_shared<Greeting>();
}
int main() {
std::cout << "Start" << std::endl;
shared();
std::cout << "End" << std::endl;
}
您将获得以下输出:
Start //Start of the main
Hello // When creating the object (the resource)
Bye // **When destructing the object (the resource)**
End //End the main
推荐阅读
- apache-spark - 为什么 spark 显示文件数和分区数的差异?
- swagger-codegen - OpenApi Generator 在 YAML 文件规范中引用外部 POJO
- python - 阈值图像数组和渲染的有效方法 - Python / NumPy / OpenCV
- reactjs - 使用 react-testing-library 进行测试时,是否需要测试父组件的所有子组件功能?
- azure - 在 Azure Blob 存储上使用静态网站选项托管 SPA(干净的 URL 和深层链接)
- excel - 连续列出所有日期 VBA EXCEL
- angular - 将 Angular SSR 项目部署到 cpanel(GoDaddy 服务器)
- php - 使用 preg_match 将字符串中的数字存储在数组中
- r - 用正整数、负整数、NA 和空白计算向量中的数字
- java - 获取 X509 证书的指纹