从下面的代码来看,如果发生了 RVO,我希望看到 2 个地址指向同一个位置,但事实并非如此(我的编译器是 MS VC9.0)
#include <iostream>
#include <string>
std::string foo(std::string& s)
{
std::cout << "address: " << (unsigned int)(&s) << std::endl;
return s;
}
int main()
{
std::string base = "abc";
const std::string& s = foo(base);
std::cout << "address: " << (unsigned int)(&s) << std::endl;
std::cout << s << std::endl;
return 0;
}
RVO 应该在什么条件下发生?
顺便说一句,我的问题基于以下讨论:http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
最佳答案
RVO 通常在您返回一个未命名的临时对象时适用,但如果您返回一个以前创建的对象,则不。
std::string foo() {
return std::string("hello world"); // RVO
}
std::string foo() {
std::string str("hello world");
bar();
return str; // Not RVO
}
std::string foo(std::string str) {
return str; // Not RVO
}
一个更通用的版本是 NRVO(命名返回值优化),它也适用于命名变量。
std::string foo() {
std::string str("hello world");
bar();
return str; // NRVO
}
std::string foo(std::string str) {
return str; // Not NRVO, as far as I know. The string is constructed outside the function itself, and that construction may be elided by the compiler for other reasons.
}
std::string foo(std::string str) {
std::string ret;
swap(ret, str);
return ret; // NRVO. We're returning the named variable created in the function
}
关于c++ - RVO应该什么时候启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2025899/