如何防止 const 引用参数的临时实现

发布于 2024-10-09 19:57:30 字数 184 浏览 0 评论 0原文

我需要编写一个类,其构造函数采用对对象的常量引用并将其存储在本地。

为了避免我可以预见的最常见错误,我只想接受对非临时的引用(即:对左值的引用)。

如何编写一个仅接受非临时常量引用的函数?


当然,即使是非临时引用也可能超出范围,从而破坏我的班级行为,但我相信通过禁止临时引用我将避免大多数错误。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怂人 2024-10-16 19:57:30

如果您要存储引用并需要在构造函数完成后使用它,那么构造函数最好采用指针:

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

    const X* p_;
};

这样,几乎可以保证您不会有一个指向临时对象的指针(除非X 做了一些非常愚蠢的事情,比如重载一元 & 以返回 this)。

如果构造函数采用指针,则类的用户也更清楚地知道他们需要注意传递给构造函数的 X 对象的生命周期。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文