[英]Is there any point in returning an object (e.g., std::string) by reference when the method has no parameters?
Take the following snippet of code采取以下代码片段
#include <iostream>
#include <string>
class Foo {
private:
std::string m_name;
public:
Foo(std::string name) : m_name { name } {}
const std::string & get_name() const { return m_name; }
};
int main() {
Foo x { "bob" };
x.get_name();
}
Because I initialized an object and name
exists somewhere in memory, is a temporary object is made when I call the x.get_name()
?因为我初始化了一个对象并且
name
存在于内存中的某处,所以当我调用x.get_name()
时是否会创建一个临时对象? If a temporary object is made, than is there a point to returning by reference?如果制作了一个临时对象,那么是否有必要通过引用返回? My understanding is you return by reference so to avoid the cost of creating a large object or when using an
std::ostream&
object because you have to.我的理解是您通过引用返回,以避免创建大对象或使用
std::ostream&
对象的成本,因为您必须这样做。
Yes, there is a point, you return by reference if you want to return a reference to some object.是的,有一点,如果要返回对某个对象的引用,则通过引用返回。
Why would you want to have a reference to some object?为什么要引用某个对象? Exactly because you need to access it and not a copy of it .
正是因为您需要访问它而不是它的副本。 Reasons might vary, basic ones are that you do not want to make an extra copy - eg the
get_name
you posted, maybe you want to store it and access it later, and/or because you want to modify it.原因可能会有所不同,基本原因是您不想制作额外的副本 - 例如您发布的
get_name
,也许您想存储它并稍后访问它,和/或因为您想修改它。
Returning a reference is not much different from a passing parameter by reference.返回引用与通过引用传递参数没有太大区别。
No temporary std::string
object is made in x.get_name()
.在
x.get_name()
中没有创建临时std::string
对象。 The method returns lvalue reference by value.该方法按值返回左值引用。 Since references are usually implemented as pointers, the true return value is a pointer.
由于引用通常实现为指针,因此真正的返回值是指针。 So a copy of the pointer is made during each call but that is like returning an
int
- can be done in registers or stack.因此,在每次调用期间都会制作指针的副本,但这就像返回一个
int
- 可以在寄存器或堆栈中完成。 So it's as cheap as it gets.所以它尽可能便宜。
Yes, your understanding is correct, although I would say that const T&
is used when we want to avoid copy for whatever reasons and T&
should only be used when we need to get mutable access to the object - eg std::ostream&
in operator<<
which mutates the stream by printing into it.是的,您的理解是正确的,尽管我会说当我们出于任何原因想要避免复制时使用
const T&
并且T&
仅应在我们需要对对象进行可变访问时使用 - 例如std::ostream&
in operator<<
通过打印到流中来改变流。
BTW, you make an extra copy in your ctor - name
parameter is copied into name
member.顺便说一句,您在 ctor 中制作了一个额外的副本 -
name
参数被复制到name
成员中。 Instead you should move it there like Foo(std::string name):name(std::move(name)){}
.相反,您应该像
Foo(std::string name):name(std::move(name)){}
一样将它移到那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.