Overloading operator &

Nov 29, 2008 at 8:55 PM
As I was adding the compile tests, I hit upon the various ways to get a pointer or a reference to the base member. Here's the problem - functions with a signature like this:

BOOL ReadFile(HANDLE hFile, BYTE* pBuf, DWORD cbBuf, DWORD* pcbRead)

are quite common. If you have overloaded operator &, this goes easily. What this unfortunately implies is that a function like so:

void Foo(SafeInt<T>* pSi)

Cannot possibly work, as you can't actually get a pointer to the object without some heroic casting. IMHO, this isn't a bad problem, as the right way to write the function is:

void Foo(SafeInt<T>& rSi)

Which does work, uses nice C++ constructs, and not icky C constructs. However, we've still got a bunch of issues - a non-trivial problem is that you cannot do this:

set< SafeInt<int> > safeint_set;

This is not good - while it may be extremely unusual to want to make STL containers full of SafeInts, it would be very bad to preclude that possibility. It is also bad to break existing code by removing the operator&. What we have done in the Visual Studio version is to remove the operator & overload, and break backwards compatability. I'm thinking that maybe the right thing to do for this version is to make this a conditional compile.

Dec 1, 2008 at 9:42 PM
Hi David,

I tend to think that it might be preferable for SafeInt not to have those operator& overloads. Because people rarely overload operator&, so they might be surprised. I do think that there are relevant use cases, passing a SafeInt by pointer, as a function argument. Typically because the argument could be a NULL pointer, to denote that its value is "unspecified", or "irrelevant".  Which might be different from passing the SafeInt value zero.

I think that the operator& overloads would make it a little bit too easy for users to accidentally leave the SafeInt world, and enter the Unsafe zone. Why shouldn't people just use SafeInt::Ptr()?

Anyway, can you please clarify the safeint_set issue to me?  Are you saying that set< SafeInt<int> > doesn't compile when SafeInt has those operator& overloads?  I haven't been able to reproduce this issue so far (using MSVC 9).