This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Wrapper For Resource Handles
  Submitted by



I like the Boost.com's Smart Pointers Library. There are cases however, when two, rarely three pointers refer to the same object. It seems reasonable to avoid placing reference counters in the heap memory in these cases. I had similar situation when a wrapper for Win32 HGLOBAL handler was needed, and a CHGlobal class was implemented. It holds a looped list, or a ring of CHGlobal* - pointers. I am not sure this is something new, but maybe this idea can be useful for implementing smart pointers in some cases:

#ifndef _HGlobal_h_
#define _HGlobal_h_

class CHGlobal { mutable CHGlobal* m_pNext; HGLOBAL m_hGlobal;

public: CHGlobal() { m_hGlobal = NULL; m_pNext = NULL; }

CHGlobal(HGLOBAL hGlobal) { m_hGlobal = hGlobal; m_pNext = (hGlobal != NULL)? this : NULL; }

CHGlobal(const CHGlobal& other) { m_hGlobal = other.m_hGlobal; if((m_pNext = other.m_pNext) != NULL) other.m_pNext = this; }

~CHGlobal() { CHGlobal* p = m_pNext; if(p != NULL) { if(this == p) ::GlobalFree(m_hGlobal); else { CHGlobal* pNext; while((pNext = p-m_pNext) != this) p = pNext; p-m_pNext = m_pNext; } } }

// A couple of the ISO C++ standardization committee members // have suggested constructor reuse // as a desirable future language feature. void Free() { this-~CHGlobal(); ::new(this) CHGlobal(); }

const CHGlobal& operator = (HGLOBAL hGlobal) { if(m_hGlobal != hGlobal) { this-~CHGlobal(); ::new(this) CHGlobal(hGlobal); } return *this; }

const CHGlobal& operator = (const CHGlobal& other) { if(m_hGlobal != other.m_hGlobal) { this-~CHGlobal(); ::new(this) CHGlobal(other); } return *this; }

operator HGLOBAL() const { return m_hGlobal; }

HGLOBAL Release() { CHGlobal* p = m_pNext; if(p != NULL) { while(p != this) { CHGlobal* pNext = p-m_pNext; p-m_pNext = NULL; p = pNext; } m_pNext = NULL; }

return m_hGlobal; }

bool operator == (HGLOBAL other) const { return m_hGlobal == other; } bool operator != (HGLOBAL other) const { return m_hGlobal != other; } };

#endif // _HGlobal_h_

Sincerely,

Alexei

The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.