我有一个函数返回对对象的 const 引用,如下所示:
const &Foo getFoo() {
return foo;
}
如果我有另一个功能如下:
void bar() {
const qwerty = asdf.getFoo();
int x = qwerty.x + 5;
// something here
}
在 qwerty 之前使用 const 是必要的还是最佳实践?
我有一个函数返回对对象的 const 引用,如下所示:
const &Foo getFoo() {
return foo;
}
如果我有另一个功能如下:
void bar() {
const qwerty = asdf.getFoo();
int x = qwerty.x + 5;
// something here
}
在 qwerty 之前使用 const 是必要的还是最佳实践?
好吧,首先,这既不是必要的,也不是最佳实践——这是不够的。你也需要一个类型。一旦你填写了它,const
仍然没有必要,除非你试图通过非const
参考来获取它。我们有三个可以编译的选择:
Foo qwerty = asdf.getFoo(); // (A)
const Foo qwerty = asdf.getFoo(); // (B)
const Foo& qwerty = asdf.getFoo(); // (C)
鉴于getFoo()
返回对 的引用const
,最有效的方法是将其也作为对的引用const
,从而避免复制。除非,也就是说,你想要一个副本——在这种情况下 do (A)
or (B)
,这取决于你是否想要一个可修改的副本。除非Foo
是不可复制的,在这种情况下无论如何(C)
都是你唯一的选择。
最终,这取决于你想用qwerty
. 我会默认为(C)
,并且需要一个理由来选择其中一个。