#include <iostream>
#include <memory>
using namespace std;

class A
{
public:
    A()
    {
            std::cout << “A  constuctor ” << std::endl;
    }

    ~A()
    {
        cout << “A  delete” << endl;

    }
};

class B
{
public:
    B()
    {       std::cout << “B  constuctor ” << std::endl;
            if( m_instance){
                    std::cout << “constructor when static member is not null ” << std::endl;
            }

    };

    ~B()
    {

            std::cout << “B  deconstuctor delete ” << std::endl;
            if( m_instance){
                    std::cout << “static member is not null ” << std::endl;
            }
    };

   void  CallSmartPointer() {
       std::unique_ptr<A> p;
      if (p == nullptr) {
          std::cout << “p is null ” << std::endl;
      }
     m_instance.reset();
   }
private:
    static std::shared_ptr<A> m_instance;
};

std::shared_ptr<A> B::m_instance = std::shared_ptr<A>(new A());
int main()
{
    B b;
    b.CallSmartPointer();
    return 0;
}
测试结果如下,

 当注释掉 m_instance.reset();这一行,不去主动释放智能指针,测试结果如下:

A delete 的打印会在进程结束时,才会释放资源。

        以上代码想说明的是,static静态成员智能指针的释放时机,可以手动控制,也可以由系统控制。

      发生问题的业务代码较多,要写清楚,篇幅太大,但是要理解这个问题的关键点,就是上面的概念即可串联起来解决问题。

       问题的发生还是因为,业务中有两个相互依赖的static变量值,当系统按照正确的顺序释放两个static变量值,不会出问题,但是系统释放顺序反了,就会导致内存破坏的crash问题。所以需要手动控制两个变量的内存释放顺序。

 

 


版权声明:本文为XiAoma123_1原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/XiAoma123_1/article/details/121679412