gpt4 book ai didi

c++ - `T&` 和 `const T&` 对于 all-const 类的区别

转载 作者:可可西里 更新时间:2023-11-01 17:35:43 24 4
gpt4 key购买 nike

假设我有这样一个类:

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& 无论如何。

但是对于整个类(class)而言,有什么不同吗?也许与模板有关?有什么事吗?


现在templatetypedef has written a nice answer ,不幸的是,这在这种情况下没有帮助,我认为最好强调一下,当你已经有了引用时你能做什么(注意所有这些“访问”),与您可以绑定(bind)到引用的内容无关。

因此,您可以假设 ref 已经存在,并绑定(bind)到某个对象。现在是关于它可以做什么的全部内容。

最佳答案

我不确定这是否是您要找的,但考虑一下这个函数:

void DoSomething(Foo& fooRef);

在这种情况下,您不能调用

DoSomething(Foo()); // Error- can't bind a reference to a temporary

但是,如果我们有这个函数:

void DoSomethingConst(const Foo& fooRef);

那我们确实可以调用

DoSomethingConst(Foo()); // Okay - const reference can bind to a temporary

所以有一个细微的差别,当非 const 引用不能时,const 引用可以潜在地绑定(bind)到临时 Foo。因此,您可能希望采用 Foo 的函数采用 const Foo& 而不是 Foo& 以便调用与临时工一起工作。

希望这对您有所帮助!

关于c++ - `T&` 和 `const T&` 对于 all-const 类的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9266227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com