C ++: reference to a temporary constant

I need to write a class whose constructor takes a permalink to an object and stores it locally.

To avoid most of the common mistakes that I can foresee, I would only like to accept links to non-temporary (i.e. links to lvalues).

How can I write a function that accepts permalinks to non-temporary only?




Of course, not even temporary ones can go out of scope and thus violate the behavior of my class, but I believe that by banning temporary references, I will avoid most errors.

+11
c ++ reference const temporary
Dec 28 2018-10-12T00:
source share
1 answer

If you intend to store a link and use it after the constructor completes, it is probably best for the constructor to take a pointer:

struct C { C(const X* p) : p_(p) { } const X* p_; }; 

This way, it is pretty much guaranteed that you won't have a pointer to a temporary one (unless X does something really stupid, like overloading unary & to return this ).

If the constructor takes a pointer, it is also more understandable to users of this class that they need to pay attention to the lifetime of the X object that they pass to the constructor.

+18
Dec 28 '10 at 0:12
source share



All Articles