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...
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_;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With