RVO何时启动? [英] When should RVO kick-in?
问题描述
从以下代码,如果RVO发生,我希望看到2个地址指向同一位置,但是不是这样(我的编译器是MS VC9.0)
From the following code, If RVO has happened, I expect to see the 2 addresses pointing to the same location, however this is not the case (my compiler is 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在什么情况下会发生?
Under what conditions should RVO be happening?
btw,我的问题是关于以下讨论:http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
btw, I'm basing my question on the following discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
推荐答案
RVO通常适用于您返回未命名的临时数据,但如果您返回之前创建的对象,则不会。
RVO generally applies when you return an unnamed temporary, but not if you return a previously created object.
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 ,这也适用于命名变量。
A more general version is NRVO (Named return value optimization), which also works on named variables.
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
}
这篇关于RVO何时启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!