C++: non-temporary const reference

六月ゝ 毕业季﹏ 提交于 2019-11-27 16:17:44

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4542789/c-non-temporary-const-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!