加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – boost :: any_cast(const any&)使用const_cast &l

发布时间:2020-12-16 09:52:17 所属栏目:百科 来源:网络整理
导读:boost / any.hpp(版本1.55)定义(第263行) templatetypename ValueTypeinline const ValueType * any_cast(const any * operand) BOOST_NOEXCEPT{ return any_castValueType(const_castany *(operand));} 但是,如果原始对象未声明为const,则使用const_cast可
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,则使用const_cast<>可能会导致未定义的行为

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); }
};

那么,是提升犹太人吗?

解决方法

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

如果使用const_cast,UB标准只能在1种情况下:

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 ]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读