سؤال

I need to write a class whose constructor takes a constant reference to a object and stores it locally.

In order to avoid most common mistakes I can foresee, I'd like to only accept references to non-temporary (ie: references to lvalues).

How can I write a function that takes constant references to non-temporary only?


Of course even a non-temporary could go out of scope and thus break my class behavior, but I believe that by disallowing temporary references I will avoid most mistakes.

هل كانت مفيدة؟

المحلول

If you are going to store a reference and need to use it after the constructor has completed, it's probably best for the constructor to take a pointer:

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

    const X* p_;
};

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

If the constructor takes a pointer, it's also clearer to users of the class that they need to pay attention to the lifetime of the X object they pass to the constructor.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top