Getting shared_ptr to call a member function after the reference count reaches 0

I am creating a wrapper for HANDLE that does not work with DuplicateHandle, so instead I am trying to wrap the handle in shared_ptr.

Provide the following code:

class CWrapper
{
public:
    CWrapper() :
        m_pHandle(new HANDLE, &CWrapper::Close)
    {
        //code to open handle
    }

private:
    void Close() 
    { 
        //code to close handle
    }

    std::shared_ptr<HANDLE> m_pHandle;
}

I also tried creating a connection with a HANDLE parameter (not perfect). In any case, I get a compiler error "The term does not evaluate a function that takes 0 arguments." Is it because of this implicit pointer? How to fix it? How to call a member function from a shared pointer?

+3
source share
5 answers

I think you have your abstractions wrong.

shared_ptr "" , . shared_ptr , , .

, , , , shared_ptr , . ( , HANDLE , HANDLE, , , .)

class CWrapper
{
public:
    CWrapper()
    {
        // code to open handle
    }

    ~CWrapper()
    {
        // code to close handle
    }

private:
    // prevent copying
    CWrapper(const CWrapper&);
    CWrapper& operator=(const CWrapper&);

    HANDLE mHandle;
};

shared_ptr<CWrapper>, , typedef, , .

- , .

+5

-, , :

void my_deleter(Foo *ptr)
{
 delete ptr;
 std::cout<< "using custom deleter" <<std::endl;
}
shared_ptr<Foo> pf (new Foo, my_deleter); 
+6

Close, this

CWrapper() :
   m_pHandle(new HANDLE, boost::bind(&CWrapper::Close, this, _1)) {
    //code to open handle
}

, , . , *this. , , , , :

CWrapper getWrapper() { CWrapper w; return w;  }
CWrapper x = getWrapper();

, x , undefined, x , w, !

, , , , ,

class CWrapper
{
public:
  CWrapper():m_pHandle(new CHandle)
  { }

private:
    // This class cannot be copied
    class CHandle : boost::noncopyable {
      friend class CWrapper;

      CHandle() 
        :m_pHandle(new HANDLE) {
          // code to open handle
      }

      ~CHandle() {
        // code to close this handle, making use of 
        // auxilary data for whatever reason
      }

    private:
      boost::scoped_ptr<HANDLE> m_pHandle;
      // auxilary data associated with the handle...
    };

    boost::shared_ptr<CHandle> m_pHandle;
};

, , . .

CWrapper getHandle() { return myHandle; }
CWrapper w = getHandle();

, , , .

+5
source

I have not tested it, but based on the idea presented by shoosh, you can pass a member function as follows:

void Class::myDeleteMember(Foo *ptr)
{
 delete ptr;
 std::cout<< "using custom deleter" <<std::endl;
}
shared_ptr<Foo> pf (new Foo, boost::bind(&Class::myDeleteMember, _1)); 
+3
source

Look deleterin boost :: shared_ptr docs. I could not find a direct link to it, but basically it is a functor that gets called when ref is 0.

0
source

Source: https://habr.com/ru/post/1750899/


All Articles