简体   繁体   English

如何安全地保留C ++ const引用?

[英]How do I safely hold on to a C++ const reference?

aka. 又名。 how do I prevent a const& parameter from accidentally binding to a temporary? 如何防止const&参数意外绑定到临时文件?

We have a class that essentially looks like this: 我们有一个基本上看起来像这样的类:

template<typename T>
struct Observer {
  const T* target;

  void observe(const T& x) {
     target = &x;
  }
};

That is, these objects will "hold on" to the const-ref they get passed. 也就是说,这些对象将“保留”通过它们的const-ref。

We had a bug where the observe function accidentally got passed a temporary object - something that can never be valid for this case. 我们遇到了一个错误,即observe函数意外地传递了一个临时对象-这种情况在这种情况下永远是无效的。

What options do we have to prevent accidentally binding to a temporary? 我们有什么选择可以防止意外绑定到临时文件?

Changing the signature to (const T* px) would work technically (taking the address of a temporary is a compiler warning=error here) it is not very attractive for other reasons. 将签名更改为(const T* px)在技​​术上是可行的(此处将临时地址作为编译器警告=错误),由于其他原因,它不是很吸引人。

Side note: Yeah, this will always have potential lifetime management issues, but so far the real thing worked pretty well because of its limited usage pattern - but passing temporaries accidentally has been observed in practice, so we want to possibly address that first. 附注:是的,这将始终有潜在生命周期管理问题,但到目前为止,真实的东西工作,因为其有限的使用模式非常好-但传递的临时偶然实践中观察到的,所以我们想可能解决,第一。

You can add a rvalue reference overload, and delete it: 您可以添加右值引用重载,并将其删除:

void observe(const T&& x) = delete;

Now a compile error will be issued if someone tries to pass a temporary. 现在,如果有人尝试通过一个临时文件,将发出编译错误。

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

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