• (原)C++智能指针——释放器(in linux, g++)


    我的记录:

    1.指定了释放器,就不会去直接调用析构函数。因为释放器就一个。不指定的话析构函数就是释放器.

    2.STL智能指针对内置内型的支持不如class:比如shared_ptr<char> s(new char[10]); memset(s, 0x00, 10);//error! 只能memset(s.get(), ....了。

    3. auto_ptr不能指定释放器.

    #include "iostream"
    #include <tr1/memory>
    
    using namespace std;
    using std::tr1::shared_ptr;
    using std::auto_ptr;
    
    class C
    {
    public:
    	C()
    	{ 
    		cout<<"C()"<<endl;  
    		buf = new char[10];
    	}
    	~C()
    	{ 
    		cout<<"~C()"<<endl;  
    		if(buf)
    		{
    			cout<<"~C() delete []buf."<<endl; 
    			delete [] buf;
    		}
    	}
    	static void MyRelease(C * pC)
    	{
    		cout<<"MyRelease()"<<endl;
    		cout<<"MyRelease() delete [] buf."<<endl;
    		delete [] pC->buf;
    		pC->buf = NULL;
    		cout<<"MyRelease() delete C:";
    		delete pC;//call ~C().
    	} 
    
    private:
    	char * buf;
    };
    
    int main()
    {
    	cout<<"std::tr1::shared_ptr<C>:"<<endl;
    	{
    		C * a = new C;
    		shared_ptr<C> shareC(a, C::MyRelease); 
    	}
    	cout<<"<- shared_ptr test ended.\n"<<endl;
    	
    	cout<<"std::tr1::shared_ptr<C> copy test"<<endl;
    	{
    		shared_ptr<C> shareC(new C, C::MyRelease);
    		shared_ptr<C> shareC2 = shareC;
    	}
    	cout<<"<- shared_ptr copy test ended.\n"<<endl;
    
    	cout<<"std::auto_ptr<C>:"<<endl;
    	C * b = new C;
    	auto_ptr<C> autoC(b);
    
    	cout<<"return 0;"<<endl;
    	return 0;
    }
    

     
    $ g++ main.cpp

  • 相关阅读:
    maven(一)maven自带的插件
    Faster RCNN 的细节补充
    leetcode 287
    一句话介绍python线程、进程和协程
    C++中指针和引用的区别
    C++ operator new和new operator的区别
    Faster RCNN算法训练代码解析(3)
    Faster RCNN算法训练代码解析(2)
    Faster RCNN算法训练代码解析(1)
    Faster RCNN算法demo代码解析
  • 原文地址:https://www.cnblogs.com/xiaouisme/p/2637498.html
Copyright © 2020-2023  润新知