C++: non-temporary const reference

你说的曾经没有我的故事 提交于 2019-11-29 01:53:06

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.

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