c++ - boost::any_cast(const any&) 使用 const_cast<>——这不是潜在的 UB 吗?

标签 c++ boost boost-any

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/

相关文章:

c++ - 函数头中的 C/C++ 数组变量

c++ - 模板元编程如何专注于集合

c++ - 如何在 Visual Studio 2012 中用 C++11 替换所有 BOOST_FOREACH?

c++ - Boost::Container::Vector with Enum Template Argument - 不是合法的基类

c++ - 使用函数 <void (boost::any)> 的事件系统是个好主意?

c++ - boost::unsafe_any_cast 为空时无效的非空指针?

c++ - (C++)Code::Blocks 可能错误的 Qt4 设置

c++ - 从 Windows::Storage::Streams::IBuffer 中获取字节数组

c++ - std::set 不检测重复的自定义对象

c++ - 类型转换指针