为什么result和result_str的地址是相同的,即使它们是不同作用域的不同变量?

问题描述 投票:0回答:1
#include<string>
#include<iostream>
std::string add_strings(std::string str1, std::string str2){
std::string result =  str1 + str2;
std::cout << "In : &result(std::string) :  " << &result << std::endl;
return result;
}
int main(){
std::string in_str1{"Hello"};
std::string in_str2{" World!"};
std::string result_str= add_strings(in_str1,in_str2);
std::cout << "Out : &result_str(std::string) :  " << &result_str << std::endl;
std::cout << "result_str : " << result_str << std::endl;
}

我发现一些解释告诉我们,编译器将默认的按值返回转换为按引用返回, 我想知道这是否正确。

c++ compiler-construction gnu
1个回答
0
投票

这是因为命名返回值优化,NRVO。

result
中的
add_strings()
变量是直接在内存中
result_str
所在的位置创建的,因此在这种情况下,当您
return result;
时,不会进行复制或移动。

© www.soinside.com 2019 - 2024. All rights reserved.