在局部作用域内,用new 产生的对象, 在退出作用域之前, 不delete,就会造成内存泄漏..
代码例子如下:
InBlock.gif#include < string>    
InBlock.gif#include <iostream>    
InBlock.gif class A
InBlock.gif{
InBlock.gif public:
InBlock.gif    A(){std::cout<< "constructor A"<<std::endl;};
InBlock.gif    ~A(){std::cout<< "desstructor A"<<std::endl;};
InBlock.gif     void test(){std::cout<< "invoke test"<<std::endl;};
InBlock.gif};
InBlock.gif class B: public A
InBlock.gif{
InBlock.gif public:
InBlock.gif    B(){std::cout<< "constructor B"<<std::endl;};
InBlock.gif    ~B(){std::cout<< "desstructor B"<<std::endl;};
InBlock.gif
InBlock.gif};
InBlock.gif void extentest()
InBlock.gif{
InBlock.gif  B *myb = new B();
InBlock.gif  myb->test();
InBlock.gif}
InBlock.gif int main( int argc, char* argv[]){    
InBlock.gif      extentest();
InBlock.gif         return 0;    
InBlock.gif}
 
允许结果:
InBlock.gifconstructor A
InBlock.gifconstructor B
InBlock.gifinvoke test
没有调用析构函数
为了避免这样的后果, 通常使用boost库里的 shared_ptr 模板,这样就不需要使用delete
修改void extentest()
InBlock.gif void extentest()
InBlock.gif{
InBlock.gif                shared_ptr<B> myb= new B();
InBlock.gif                myb->test();
InBlock.gif}
当变量myb 作用域消失后,会自动删除new B 的对象.