D
Denis Remezov
Jakob said:Hi!
I am using VC++ 7.1 and have a question about return value optimization.
Consider the following code:
#include <list>
#include <string>
struct test
{
std::list <std::string> m_strings;
};
test func1 (int r)
{
if (r == 0)
return test ();
test t = func1 (r - 1);
t.m_strings.push_back ("lala");
return t;
}
int main ()
{
test t = func1 (3);
}
As Jeff said, in the above example the compiler is allowed to optimise
away unnecessary locals (in func1()), temporaries and the corresponding
copy constructor calls. If func1() were defined like this:
test func1 (int r)
{
test t;
t.m_strings.push_back ("lala");
return t;
}
with the same main(), I would definitely expect just one construction and
destruction from a decent compiler. The recursion, however, may complicate
things a bit. You can add a couple of ctors to test (default and copy) and
a dtor that cout a message and see.
Consider this too:
int main()
{
test t;
//do something to t ...
t = func1 (3);
}
Not much luck in this case: t will be constructed first, then at least one
object of class test will be created as a result of func1(), then operator =
will be called.
When I care about performance, I usually define func1() as
void func1 (int r, test& t) {...}
If the functional notation were important, I would consider using proxies
(and accomodate the "actual" objects acordingly), but I would not return
really big objects from a function.
Denis