3

boost/any.hpp (version 1.55) defines (line 263)

template<typename ValueType>
inline const ValueType * any_cast(const any * operand) BOOST_NOEXCEPT
{
    return any_cast<ValueType>(const_cast<any *>(operand));
}

However, using const_cast<>, may result in undefined behaviour if the original object was not declared const as in

class foo
{
  boost::any value;
  template<typename T>
  foo(T const&x) noexcept : value(x) {}

  template<typename T>
  const T*ptr() const noexcept
  { return boost::any_cast(value); }
};

So, is boost kosher?

Walter
  • 44,150
  • 20
  • 113
  • 196
  • didn't you misquote there; UB if I remove const from originally non-const obj? – sp2danny May 20 '14 at 08:48
  • 1
    It could lead to UB *if* the function returned a pointer to the non-const value type, but it isn't. Constant in, constant out. The code inside the function? It's just casting and doesn't modify the object. – Some programmer dude May 20 '14 at 08:48
  • Hmm. I may have been misguided by older standards. So `const_cast<>(non_const_object)` is not (potentially) UB after all? – Walter May 20 '14 at 08:51
  • Older standards had no problem with that either AFAIK – M.M May 20 '14 at 08:52

2 Answers2

4

This is legal code, since any_cast returns const-pointer and any_cast, that receives pointer, does not change its argument.

UB by standard can be only in 1 situation if you use const_cast:

n3376 5.2.11/7

[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior (7.1.6.1). — end note ]

ForEveR
  • 55,233
  • 2
  • 119
  • 133
3

Maybe you are thinking of [expr.const.cast]#7:

[Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier 73 may produce undefined behavior (7.1.6.1). —end note ]

The section 7.1.6.1 is:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior

But there is no such write operation in this code. The rest of the [expr.const.cast] section says nothing to suggest that this code has a problem.

M.M
  • 138,810
  • 21
  • 208
  • 365