全 const 类的 `T&` 和 `const T&` 之间的区别
假设我有一个这样的类:
class Foo : boost::noncopyable
{
public:
Foo(int a, int b);
const int something;
const int something_else;
const std::string another_field;
// and that's that, no more methods nor fields
};
现在,通过 Foo&
访问此类的对象与通过 const Foo&
访问此类的对象之间有什么实际区别吗?这两者是两种不同的类型吗?
访问其字段应该没有任何区别,因为它们是const
,因此将通过const T&
访问它们反正。
但是对于整个班级来说,有任何差异吗?也许与模板有关?任何事物?
现在 templatetypedef 已经写了一个很好的答案,不幸的是在这种情况下没有帮助,我认为最好强调一下,这很大程度上是关于当您已经拥有引用时您可以做什么(注意所有这些“访问”),而不是关于您可以绑定到引用的内容。
因此,您可以假设引用已经存在,并绑定到某个对象。现在一切都是关于可以用它做什么。
Suppose that I have a class like that:
class Foo : boost::noncopyable
{
public:
Foo(int a, int b);
const int something;
const int something_else;
const std::string another_field;
// and that's that, no more methods nor fields
};
Now, is there any practical difference between accessing the objects of this class through a Foo&
, as opposed to const Foo&
, other than that these two are two distinct types?
There shouldn't be any difference for accessing its fields, as they're const
, so they will be accessed to through a const T&
anyway.
But is there any difference when it comes to the class as a whole? Something to do with templates, perhaps? Anything?
Now that templatetypedef has written a nice answer, which unfortunately is not helpful in this case, I think it'd be nice to underline that it's very much about what can you do when you already have a reference (note all these "accessing"), not about what you can bind to the reference.
So, you can assume that the ref is already there, bound to some object. Now it's all about what can be done with it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定这是否是您正在寻找的,但请考虑这个函数:
在这种情况下,您无法调用
但是,如果我们有这个函数:
那么我们确实可以调用
所以有略有不同的是,
const
引用可能会绑定到临时Foo
,而非const
引用则不能。因此,您可能希望接受Foo
的函数接受const Foo&
而不是Foo&
,以便能够使用临时函数调用该函数。希望这有帮助!
I'm not sure if this is what you're looking for, but consider this function:
In this case, you cannot call
However, if we have this function:
Then we can indeed call
So there is a slightly difference in that a
const
reference can potentially bind to a temporaryFoo
when a non-const
reference cannot. Consequently, you'd probably want functions taking inFoo
s to take in aconst Foo&
rather than aFoo&
to make it possible to call the function with temporaries.Hope this helps!