【问题标题】:boost::any_cast(const any&) uses const_cast<> -- Isn't this potentially UB?boost::any_cast(const any&) 使用 const_cast<> -- 这不是潜在的 UB 吗?
【发布时间】:2014-05-20 08:42:28
【问题描述】:

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&lt;&gt;可能会导致未定义的行为如果原始对象没有声明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 是否符合规定?

【问题讨论】:

  • 你不是在那儿引错了吗? UB 如果我从最初的非常量 obj 中删除 const?
  • 它可能导致UB 如果函数返回一个指向非const值类型的指针,但事实并非如此。不断进,不断出。函数里面的代码?它只是强制转换,不会修改对象。
  • 嗯。我可能被旧标准误导了。所以const_cast&lt;&gt;(non_const_object)毕竟不是(可能)UB?
  • 旧标准对此没有任何问题 AFAIK

标签: c++ boost boost-any


【解决方案1】:

这是合法代码,因为any_cast 返回 const-pointer,而接收指针的any_cast 不会更改其参数。

如果您使用const_cast,按照标准,UB 只能在一种情况下:

n3376 5.2.11/7

[注:根据对象的类型,写操作通过 由 a 产生的指针、左值或指向数据成员的指针 丢弃 const 限定符的 const_cast 可能会产生 undefined 行为 (7.1.6.1)。 ——尾注]

【讨论】:

    【解决方案2】:

    也许你在想[expr.const.cast]#7

    [注意:根据对象的类型,写操作通过指针、左值或指向由 const_cast 产生的数据成员的指针,该 const_cast 丢弃了 const 限定符 73 可能会产生未定义的行为(7.1.6.1)。 ——尾注]

    第 7.1.6.1 节是:

    除了可以修改任何声明为 mutable (7.1.1) 的类成员外,任何修改 const 的尝试 对象在其生命周期 (3.8) 中会导致未定义的行为

    但是这段代码中没有这样的写操作。 [expr.const.cast] 部分的其余部分没有说明此代码有问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 2011-05-01
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多