[c++] 引用

1、使用引用避免拷贝

c++中拷贝大的类类型对象或容器对象比较低效,甚至有的类型不支持拷贝,这种情况下只能通过引用形参访问该类型的对象

当函数无需修改引用形参的值时,最好使用常量引用

例1:返回两个字符串中较短的那个

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 using std::string;
 5 
 6 const string &shorterString(const string &s1, const string &s2) {
 7     return s1.size() <= s2.size() ? s1 : s2;
 8 }
 9 int main() {
10     string s1 = "hello";
11     string s2 = "hi";
12     string s = shorterString(s1,s2);
13     cout << s << endl;
14 }

结果:hi

最终s返回的是较短字符的引用

2、函数返回多个值

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 using std::string;
 5 
 6 string::size_type find_char(const string &s, char c,
 7     string::size_type &occurs) {
 8     auto ret = s.size();
 9     occurs = 0;
10     for (decltype(ret) i = 0; i != s.size(); ++i) {
11         if (s[i] == c) {
12             if (ret == s.size())
13                 ret = i;
14             ++occurs;
15         }
16     }
17     return ret;
18 }
19 
20 int main() {
21     string s = "helloo";
22     string::size_type ctr;
23     auto index = find_char(s, 'o', ctr);
24     cout << ctr << endl;
25 }

输出:2

参考:

《c++ primer》(第五版)

原文地址:https://www.cnblogs.com/cxc1357/p/10561533.html