天天看点

(测试)使用引用计数管理对象生命期

单线程下测试:

1 #include <iostream>
  2 
  3 class RefObject{
  4 public:
  5     RefObject() : count(1){
  6         std::cout<<"Base created."<<std::endl;
  7     }
  8     virtual ~RefObject(){
  9         std::cout<<"Base deleted."<<std::endl;
 10     }
 11     void addRef(){
 12         //single thread
 13         std::cout<<"add."<<std::endl;
 14         count++;
 15     }
 16     void ReleaseRef(){
 17         std::cout<<"release."<<std::endl;
 18         if(--count==0){
 19             delete this;
 20         }
 21     }
 22 
 23 private:
 24     int count;
 25     //MutexLock lock; 
 26     RefObject(RefObject& obj){
 27         count=obj.count;
 28     }
 29     RefObject& operator=(RefObject& rhs){
 30         count=rhs.count;
 31     }
 32 };
 33 
 34 class CBaseSocket : public RefObject{
 35 public:
 36     CBaseSocket(){
 37         std::cout<<"Object CBaseSocket created."<<std::endl;
 38     }
 39     ~CBaseSocket(){
 40         std::cout<<"Object CBaseSocket deleted."<<std::endl;
 41     }
 42 
 43 private:
 44 
 45 };
 46 
 47 int main(){
 48     CBaseSocket* socket1 = new CBaseSocket;
 49     socket1->addRef();
 50     socket1->ReleaseRef();
 51     socket1->ReleaseRef();
 52 
 53     return 0;
 54 }
           

使用valgrind检测内存泄漏情况:

[email protected]:~$ vim testHandReleaseWithRef.cpp 
[email protected]:~$ g++ -std=c++11 testHandReleaseWithRef.cpp -o testHandReleaseWithRef
[email protected]:~$ which valgrind
/usr/bin/valgrind
[email protected]:~$ /usr/bin/valgrind ./testHandReleaseWithRef 
==111718== Memcheck, a memory error detector
==111718== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==111718== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==111718== Command: ./testHandReleaseWithRef
==111718== 
Base created.
Object CBaseSocket created.
add.
release.
release.
Object CBaseSocket deleted.
Base deleted.
==111718== 
==111718== HEAP SUMMARY:
==111718==     in use at exit: 0 bytes in 0 blocks
==111718==   total heap usage: 3 allocs, 3 frees, 73,744 bytes allocated
==111718== 
==111718== All heap blocks were freed -- no leaks are possible
==111718== 
==111718== For counts of detected and suppressed errors, rerun with: -v
==111718== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
[email protected]:~$