Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent passing rvalue by reference

In my project the majority of objects are created in an arena, and it is guaranteed that they are exist during a user session. So it is quite safe for some class to have const reference as a member field, for example:

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

 private:
  const string& str_;
};

But here there is a pitfall. By mistake it is possible to create an instance of A the following way:

A a("some temporal string object");

In that line the temporal string object has been implicitly created and destroyed. So after that a stores incorrect reference.

How to prevent that behavior? It would be better if it results in compile error...

like image 519
Alexey Avatar asked Jun 23 '17 07:06

Alexey


1 Answers

You just need to have an overload which matches better to rvalues, so that the compiler takes that one over the const& one.

So, a temporary better matches a && than a const&, so you just need to provide such a constructor and delete it:

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

 private:
  const string& str_;
};
like image 181
Rakete1111 Avatar answered Nov 03 '22 12:11

Rakete1111