boost/any.hpp(版本 1.55)定义(第 263 行)
template<typename ValueType>
inline const ValueType * any_cast(const any * operand) BOOST_NOEXCEPT
{
return any_cast<ValueType>(const_cast<any *>(operand));
}
但是,使用 const_cast<>
, 可能会导致未定义的行为 如果原始对象未声明const
如同
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); }
};
那么,boost 符合犹太洁食标准吗?
最佳答案
这是合法的代码,因为 any_cast
返回常量指针,而接收指针的 any_cast
不会更改其参数。
如果您使用 const_cast
,UB 按照标准只能在一种情况下:
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 ]
关于c++ - boost::any_cast(const any&) 使用 const_cast<>——这不是潜在的 UB 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23754929/