两个模块类的static静态成员相互依赖,释放顺序错误导致crash问题

两个模块类的static静态成员相互依赖,释放顺序错误导致crash问题,第1张

两个模块类的static静态成员相互依赖,释放顺序错误导致crash问题

#include
#include
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 p;
      if (p == nullptr) {
          std::cout << "p is null " << std::endl;
      }
     m_instance.reset();
   }
private:
    static std::shared_ptr m_instance;
};

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

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

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

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

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

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

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5635856.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存