简体   繁体   English

自定义引用包装器的 const 正确性

[英]const correctness for custom reference wrapper

I'm using boost::variant to implement type erasure when sending data across network.我在通过网络发送数据时使用boost::variant来实现类型擦除。 When the data arrives to the client or server, I'm inspecting its structure to retrieve the underlying information and reporting errors when the structure does not match the one agreed upon in the API.当数据到达客户端或服务器时,我正在检查其结构以检索基础信息并在结构与 API 中约定的结构不匹配时报告错误。 For this purpose, I created a lightweight reference wrapper that holds a reference to the variant and provides a convenient interface for structure inspection and type conversions.为此,我创建了一个轻量级引用包装器,它包含对变体的引用,并为结构检查和类型转换提供了一个方便的接口。

using value_t = boost::make_recursive_variant< /*types, some of them recursive*/ >::type;

class view_t {
public:
  /*non-const methods to access value_*/
private:
  value_t& value_;
};

class cview_t {
public:
  /*const methods to access value_*/
private:
  const value_t& value_;
};

view_t   view(value_t& v){ return v; }
cview_t cview(const value_t& v){ return v; }
cview_t cview(value_t&& v) = delete;
cview_t cview(const value_t&& v) = delete;

Unfortunately, this interface proves to be cumbersome because every aggregate type that has a view member needs to follow the same const/non-const split.不幸的是,这个接口被证明很麻烦,因为每个具有view成员的聚合类型都需要遵循相同的 const/non-const 拆分。 I was wondering whether it was legal to merge these two classes into a single view and use a const_cast in the methods that create views like this:我想知道将这两个类合并到一个视图中并在创建如下视图的方法中使用 const_cast 是否合法:

class view_t {
public:
  /*const and non-const methods to access value_*/
private:
  value_t& value_;
};

      view_t view(value_t& v){ return v; }
const view_t cview(const value_t& v){ return const_cast<value_t&>(v); }
const view_t cview(value_t&& v) = delete;
const view_t cview(const value_t&& v) = delete;

Returning const object is mostly useless, as返回 const object 几乎没有用,因为

auto /*view_t*/ my_view = cview(some_value); // legal

So you lose your constness.所以你失去了你的坚持。

Modifying const value is undefined behavior,修改 const 值是未定义的行为,

your view can be used in a way leading to UB.您的视图可以用于通向 UB 的方式。

But as long you don't modify const object, you are "fine".但只要你不修改 const object,你就“没问题”。

Splitting into 2 classes is safer, as it cannot be misused.分成 2 个类更安全,因为它不能被滥用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM