V
Victor Bazarov
In the project I'm maintaining I've seen two distinct techniques used for
returning an object from a function. One is
AType function(AType const& arg)
{
AType retval(arg); // or default construction and then..
// some other processing and/or changing 'retval'
return retval;
}
void foo()
{
AType somevariable;
AType anothervariable = function(somevariable); // pass by ref
// some other processing
}
and the other is
AType function(AType retval)
{
// some other processing and changing 'retval'
return retval;
}
void foo()
{
AType somevariable;
AType anothervariable = function(somevariable); // pass by value
// some other processing
}
As you can see the difference is when the variable which later is returned
is constructed. Yes, I realize the difference is really minimal. It is
probably has no effect on performance (and I wouldn't try to speculate one
way or another). The number of objects [copy-] constructed is probably
the same (even in theory, RVO aside). The objects being passed around are
*not* polymorphic. What am I forgetting? Copy-construction is defined
for them and in general no tricks are played. All relatively straight-
forward.
Now, my question is, why would I want to prefer/preserve one way of using
values passed to the function or should I keep both? Do you see any reefs
under the surface, any potential issues with one method or with having
both methods in the same project? Would the optimizer stumble on one of
the methods and not the other, for example?
I'd appreciate any insight. Thanks!
V
returning an object from a function. One is
AType function(AType const& arg)
{
AType retval(arg); // or default construction and then..
// some other processing and/or changing 'retval'
return retval;
}
void foo()
{
AType somevariable;
AType anothervariable = function(somevariable); // pass by ref
// some other processing
}
and the other is
AType function(AType retval)
{
// some other processing and changing 'retval'
return retval;
}
void foo()
{
AType somevariable;
AType anothervariable = function(somevariable); // pass by value
// some other processing
}
As you can see the difference is when the variable which later is returned
is constructed. Yes, I realize the difference is really minimal. It is
probably has no effect on performance (and I wouldn't try to speculate one
way or another). The number of objects [copy-] constructed is probably
the same (even in theory, RVO aside). The objects being passed around are
*not* polymorphic. What am I forgetting? Copy-construction is defined
for them and in general no tricks are played. All relatively straight-
forward.
Now, my question is, why would I want to prefer/preserve one way of using
values passed to the function or should I keep both? Do you see any reefs
under the surface, any potential issues with one method or with having
both methods in the same project? Would the optimizer stumble on one of
the methods and not the other, for example?
I'd appreciate any insight. Thanks!
V