首页 > 解决方案 > 在函数中声明共享指针会产生内存泄漏行为

问题描述

我一直在尝试理解智能指针,据我所知,一旦无法通过代码访问智能指针,它们就会自行销毁。

出于这个原因,我试图对此行为进行演示:

#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;(这是预期的行为)

我很欣赏有关这种特定行为的任何想法。

标签: pointersmemory-leaksc++17smart-pointers

解决方案


为了确保内存被删除,最好用一个类测试智能指针

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

推荐阅读