【问题标题】:Declaring a shared Pointer within a function produce a leaky memory behavior在函数中声明共享指针会产生内存泄漏行为
【发布时间】:2021-07-16 21:43:30
【问题描述】:

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

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

#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。 不应该是空数或随机数吗?如果这是正常的,那么如何制作智能指针以避免内存泄漏!?

P.S:使用普通指针进行相同的测试将产生相同的结果,除非我们添加 delete pointer;(这是预期的行为)

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

【问题讨论】:

  • 我相信您正面临崩溃或不良行为,因为您无法将整数转换为指针整数。应该是 int * pointer= &address
  • 您可以将整数转换为指针整数。试试看……

标签: pointers memory-leaks c++17 smart-pointers


【解决方案1】:

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

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

【讨论】:

  • 这看起来不错,但仍然没有回答我的问题。
猜你喜欢
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 2014-08-13
  • 2015-05-26
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多