Search code examples
c++temporary-objectsreturn-by-reference

Ignoring a return-by-reference result from a function


Suppose i have a function that returns an important result and several unimportant results. I declared it so that the unimportant results are returned by reference:

int CalculateStuff(int param1, int param2, int& result1, int& result2);

I would like to call this function to calculate some stuff, but at call site i want to ignore the unimportant results. I could do it as follows:

...
int dummy1, dummy2;
int result = CalculateStuff(100, 42, dummy1, dummy2);
... // do something with the result

I would like to consider another way to do the same without declaring dummy variables:

int result = CalculateStuff(100, 42, *new int, *new int);

This has a memory leak (unacceptable), but has an advantage of showing my intent (ignoring the results) more clearly than the "dummy" names.

So, what would happen if i wrote it as follows:

int result = CalculateStuff(100, 42, auto_ptr(new int).get(), auto_ptr(new int).get());

Is it legal? Will the temporary integers still exist when the function's code is executed? Should i use unique_ptr instead of auto_ptr?

(Please don't suggest refactoring my code; i probably will - but first i want to understand how this stuff works)


Solution

  • It is legal; auto_ptr objects will remain alive until the end of expression (i.e. function call). But it is ugly as hell.

    Just overload your function:

    int CalculateStuff(int param1, int param2, int& result1, int& result2);
    int CalculateStuff(int param1, int param2) { 
        int r1=0, r2=0; 
        return CalculateStuff(param1, param2, r1, r2);
    }