Boost logo

Boost Users :

Subject: Re: [Boost-users] [hash] hashing of smart pointer types - prevent conversion to bool?
From: Daniel James (dnljms_at_[hidden])
Date: 2010-07-06 19:01:32

On 6 July 2010 13:15, Alastair Rankine <arsptr_at_[hidden]> wrote:
> I'm sure I'm not the first person to be caught out by this.

You're the first person to report it.

> The context for this question is a fairly large codebase with extensive use
> of hashed containers. Not everyone on the development team is aware of this
> particular limitation of smart pointers. So not only do I want to detect the
> use of "dangerous" hashing functions but also prevent them being used in the
> future. Instead I really want to either fix or prevent the conversion to
> bool for smart pointers when used in a hashing function (either through the
> boost:: or tr1:: namespace).

It won't happen for a 'std' or 'std::tr1' implementation, as this
issue is caused by the boost extensions to the standard. It also won't
happen in boost if you disable the extensions by defining

I do actually view this as a bug. Of the top of my header, I can think
of a few possible fixes:

1. Remove 'hash_value(bool)', changing boost::hash<bool> to calculate
the hash value itself - that would fix this issue, but there are still
potential problems with other classes that have an implicit conversion
to certain types. I'd prefer a general solution.

2. Prevent implicit casts by adding a templated 'hash_value'
containing a static assertion. I like this, it's simple and not very
disruptive. There might be code out there that requires on
'hash_value' picking up implicit castsm but if there is, it's probably
fairly dubious.

3. Move 'hash_value' for built in types to a different namespace, or
rename them. Would have to add more specialisation to boost::hash, so
that it deals with all the appropriate types. Also have to add a macro
to allow anyone using the existing functions to continue to use them
if they wish. This would have been a good idea if it was done from the
start, but I don't like the idea of removing public functions which
have been available for a while.

Maybe some other possibilities. I'll think about it some more. I'm not
sure if I'll be able to get a fix ready for the next release.


Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at