olekk
11/3/2008 8:30:00 AM
John Lampe wrote:
> Hi all,
>
> I've got a very simple "container" class that encapsulates an (presumably
> opaque) OS handle, which is typedef'd in the OS headers to be equivalent
> to an unsigned int (I'm simplifying a bit, but the gist of it is that
> this handle is essentially a basic/primitive integer type).
>
>
> typedef unsigned int MYHANDLE;
>
> class my_auto_handle
> {
> public:
> my_auto_handle(MYHANDLE h)
> {
> m_handle = h;
> }
>
> ~my_auto_handle()
> {
> destroyhandle(m_handle);
> }
>
> operator const MYHANDLE()
> {
> return m_handle;
> }
>
> bool operator ==(MYHANDLE other)
> {
> return (m_handle == other);
> }
>
> private:
> my_auto_handle(const my_auto_handle& other);
> my_auto_handle& operator=(const my_auto_handle& other);
>
> MYHANDLE m_handle;
> };
>
>
>
> 2) Do I actually need to overload the == operator if I want to compare a
> my_auto_handle to a MYHANDLE, which is already a basic type (I'm afraid
> of accidentally comparing a MYHANDLE to, say, the address of a
> my_auto_handle object instead of the handle value contained within)?
In your case you don't have to overload the == operator, because you
have implicit conversion to MYHANDLE in your constructor. Moreover, if
you try something like
my_auto_handle m(10);
if ( m == 20 ) {//do something}
you end up with compilation error, because operator== has two
overloads now. So you can either remove the overloaded ==, or make the
constructor explicit
explicit my_auto_handle(MYHANDLE h)
{
m_handle = h;
}
Regards