static对象与shared_ptr的释放顺序

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

class A {
public:
A(){}
~A(){
  std::cout << "~A()" << endl;
}
};

class B{
public:
~B() {
  cout << "~B()" << endl;
}
};
int main() {
  static A a;
  auto b = std::shared_ptr<B>(new B());
  //B* bb = new B;
  static A aa;
  return 0;
}  

结论:shared_ptr会优先于static变量释放。

所以在设计程序的时候,一个static对象的类的析构函数不能访问其他的shared_ptr指针.随着项目的变大,程序中有众多statci变量和shared_ptr的时候,如果产生的依赖关系,是很容易产生问题的,比如一个static的map<int, shared_ptr<class>>,如果等待系统回收,那么这个map中的shared_ptr部分就会先于这个map被释放,如果在某个static对象的类的析构函数中使用了map,由于map中的second已经是野指针了,那么是一定会导致core dump的.

猜你喜欢

转载自www.cnblogs.com/deepllz/p/11934640.html
今日推荐