zoukankan      html  css  js  c++  java
  • 前置声明的危急

    先看代码:

    #include <iostream>
    
    class A{
    	int m;
    	char* arr;
    	public:
    		A(int a);
    		~A();
    };
    

    #include <iostream>
    #include "A.h"
    
    A::A(int a){
    	if (a > 0){
    		printf("%s
    ", __FUNCTION__);
    		arr = new char[a];
    	}
    } 
    
    A::~A(){
    	printf("%s
    ", __FUNCTION__);
    	if (NULL != arr){
    		printf("%s inside
    ", __FUNCTION__);
    		delete []arr;
    	}
    }
    

    #include <iostream>
    #include <memory>
    class A;
    
    class B{
    	std::auto_ptr<A> pA;
    	public:
    		B(int a);
    }; 
    

    #include  "B.h"
    #include "A.h"
    
    B::B(int a):pA(new A(a)){
    }
    

    #include "B.h"
    //#include "A.h"
    
    int main(){
    	B* pB = new B(10);
    	delete pB;
    	//A a(10);
    }
    

    从输出看没有调用A的析构,那就内存泄露了。原因在于A在B.h前置声明,std::auto_ptr仅仅能负责在生命期到了delete A;可是由于找不到A的详细信息,没有调用其析构。假设A的析构是trival的那还好,假设A里有其它资源那么就有内存泄露的危急。

    改正方法也非常easy。在B.cpp写析构即可了。

    那么就不能用std::auto_ptr了。


  • 相关阅读:
    React 使用链表遍历组件树
    React diff 算法
    JavaScript 对象操作
    前端路由hash
    动画运动曲线
    ajax跨域问题
    js版本状态模式
    装饰者模式AOP
    swipe源码循环索引
    组合模式--超级宏命令
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/6941095.html
Copyright © 2011-2022 走看看