C ++:非临时const引用 [英] C++: non-temporary const reference

查看:162
本文介绍了C ++:非临时const引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

为了避免大多数常见的错误,我可以预见,我'd只接受非临时的引用(即:引用lvalue)。

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

如何编写一个函数,

当然,即使是非临时性的也可能超出范围,从而打破我的阶级行为,但我相信,不允许临时引用我将避免大多数错误。

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_;
};

这样,几乎可以保证你不会有一个指向临时的指针code> X 做一些真正的蠢事,比如重载一元& 来返回 this )。

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).

如果构造函数接受一个指针,那么该类的用户也需要注意 X 对象,它们传递给构造函数。

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.

这篇关于C ++:非临时const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆