vendredi 23 juin 2017

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...

Aucun commentaire:

Enregistrer un commentaire