Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently Using A Function Output

Tags:

c++

c++11

I have been attempting to learn C++ over the past few weeks and have a question regarding good practice.

Let's say I have a function that will produce some object. Is it better to define the function to produce an output of type object, or is it better to have the function be passed an object pointer as an argument such that it can modify it directly?

I suppose this answer is dependent on the scenario, but I'm curious if efficiency comes into play. When passing objects into a function as an argument, I know it is more efficient to use const reference such that the function has immediate access to the object with no need of generating a copy.

Does such concern of efficiency come into play when outputting function results?

like image 795
Izzo Avatar asked Mar 24 '26 04:03

Izzo


1 Answers

The following:

MyType someFunc()
{
    MyType result;
    // produce value here
    return result;
}

Used like this:

MyType var = someFunc();

Will do no copy, and no move, but rather RVO. This means that it can't get more efficient anyway, and it is also easy to read, and hard to use wrong. Don't help the compiler.

like image 199
sp2danny Avatar answered Mar 25 '26 18:03

sp2danny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!