面试题答案
一键面试引用作为函数参数实现高效传递数据
在C++ 中,当函数参数为引用时,传递的是对象的别名而非对象的副本,从而避免了对象拷贝带来的开销,实现高效传递数据。例如:
#include <iostream>
#include <string>
// 定义一个修改字符串的函数,参数为引用
void appendString(std::string& str, const std::string& toAppend) {
str.append(toAppend);
}
int main() {
std::string original = "Hello";
std::string toAdd = ", World!";
appendString(original, toAdd);
std::cout << original << std::endl;
return 0;
}
在上述代码中,appendString
函数接受 std::string
类型的引用 str
,对其进行操作,这样无需复制整个 std::string
对象,对于大对象而言可以显著提高效率。
引用作为返回值的生命周期问题及避免方法
- 生命周期问题:当返回局部变量的引用时,会出现悬空引用问题。例如:
#include <iostream>
const int& badFunction() {
int localVar = 10;
return localVar;
}
int main() {
const int& result = badFunction();
std::cout << result << std::endl;
return 0;
}
在 badFunction
函数中,localVar
是局部变量,函数结束时 localVar
的生命周期结束,返回其引用会导致悬空引用,后续使用 result
是未定义行为。
- 避免方法
- 返回对象成员引用:如果返回类对象的成员引用,只要类对象的生命周期足够长,就不会有问题。例如:
#include <iostream>
class MyClass {
public:
int data;
MyClass(int value) : data(value) {}
int& getData() {
return data;
}
};
int main() {
MyClass obj(42);
int& ref = obj.getData();
std::cout << ref << std::endl;
return 0;
}
- **返回静态变量引用**:返回静态局部变量的引用,因为静态变量的生命周期贯穿程序始终。例如:
#include <iostream>
const int& goodFunction() {
static int staticVar = 20;
return staticVar;
}
int main() {
const int& result = goodFunction();
std::cout << result << std::endl;
return 0;
}
但要注意静态变量在多线程环境下可能带来的线程安全问题。