从下面的代码来看,如果发生了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 通常适用于返回未命名的临时对象,但是not如果您返回以前创建的对象。
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)