[英]c++ return by value vs return by reference
If I have two functions like: 如果我有两个功能,例如:
1. 1。
vector<Student_Info> extract_failed(vector<Student_Info>& students) {
return students;
}
2. 2。
vector<Student_Info>& extract_failed(vector<Student_Info>& students) {
return students;
}
Is it correct to say that function 1 is returning by value
, which means a copy of students
will be created and returned and function 2 is returning by reference
? 说函数1
returning by value
是正确的,这意味着将创建一个students
副本并返回并且函数2 returning by reference
吗?
Is it correct to say that function 1 is returning by value, which means a copy of students will be created and returned and function 2 is returning by reference?
说函数1按值返回是否正确,这意味着将创建并返回一个学生副本,而函数2按引用返回?
Yes, it is correct. 是的,这是正确的。 Another way to phrase it, which I prefer, is to say that 1 returns a value, and 2 returns a reference.
我更喜欢用另一种说法来表达它,就是说1返回一个值,而2返回一个引用。
YES 是
Although 2. in its current form would make sence if you plan to use the return value (something like print(extract_failed(students));
or for(const auto& s : extract_failed(students)
). 虽然2.如果您打算使用返回值(例如
print(extract_failed(students));
或for(const auto& s : extract_failed(students)
),则会以当前的形式出现。
Meanwhile, some scenarios may be confusing, since you can do something like 同时,某些情况可能会令人困惑,因为您可以执行以下操作
auto& new_students = extract_failed(students);
and you'll have two names in the same scope for the same vector. 并且您将在同一范围内为相同的向量使用两个名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.