C++ 临时变量
向函数传递临时变量
- 值传递
支持 - 指针传递
无法实现 - 引用传递
函数参数要使用 const & 类型
void func(const std::string& str) {
}
从函数返回临时变量
- 返回对象本身
std::string func() {
std::string str("abcd");
return str;
}
一般编译器会使用copy elision 在调用处原地构造此对象。
- 返回对象引用或者指针
编译会报错,不要这样使用
warning: returning reference to temporary [-Wreturn-local-addr]
- 使用const & 接收函数返回的临时变量
C++中有一个特殊的规则,允许const引用延长其所绑定的临时对象的生命周期。这意味着,当一个临时对象被绑定到一个const引用时,该临时对象的生命周期会被延长至与该const引用相同。
这个特性使得我们可以安全地从函数返回一个临时对象并将其绑定到一个const引用,而不用担心对象在引用之前就被销毁的问题。
std::string func() {
return "abcd";
}
void test() {
const std::string& str = func();
std::cout << str << std::endl;
}
4440

被折叠的 条评论
为什么被折叠?



