防止通过引用传递右值

Prevent passing rvalue by reference

在我的项目中,大多数对象都是在 arena 中创建的,并且保证它们在用户会话期间存在。 所以对于某些 class 来说,将 const 引用作为成员字段是非常安全的,例如:

class A {
 public:
  A(const string& str) : str_(str) {}

 private:
  const string& str_;
};

但是这里有一个陷阱。错误地可以通过以下方式创建 A 的实例:

A a("some temporal string object");

在那一行中,临时 string 对象已被隐式创建和销毁。所以在那之后 a 存储了不正确的引用。

如何防止这种行为?要是编译出错就更好了...

您只需要有一个与右值匹配得更好的重载,这样编译器就会在 const& 上使用那个重载。

所以,临时匹配 && 比匹配 const& 更好,所以你只需要提供这样的构造函数和 delete 它:

class A {
 public:
  A(const string& str) : str_(str) {}
  A(string&&) = delete; // this constructor is a better match for rvalues

 private:
  const string& str_;
};