Functions returning objects or pointers

Feb 4, 2009 at 9:21am
I'm sure this topic would have been discussed many times but I am having difficulty finding the information.

What is the best way to return a string or object from a function? I don't want the calling function to be responsible for the disposal of the object. I wrote little test program to try work it out and came up with.

class TestClass {
public:
TestClass() { printf("constructing %d\n", this); };
~TestClass() { printf("destructing %d\n", this); };
void bam() { printf("bam\n"); };
};

TestClass x()
{
TestClass x;
return x;
}

int main(int argc, char *argv[])
{

printf("before constructor\n");
TestClass a = x();
printf("after constructor\n");
a.bam();
return 0;

}

Which results in:
before constructor
constructing 2293536
after constructor
bam
destructing 2293536

So the object is not destroyed when it is passed back into the main function... other methods clearly destroy the object before it is returned. So, is this the best way of doing this and are there any good websites that explain how C++ compilers handle functions that return objects created within the function?

Thanks heaps,
Feb 4, 2009 at 10:33am
If you know the type exaxtly, you can declare it somewhere an pass it by reference to something that "fills it in".

If you don't know the type exactly (a polymorphic hierarchy), you will have to use pointers and remember to clean it up somehow.
Feb 4, 2009 at 12:46pm
@nicholasa:

I'm not sure what other methods you tried, but you might have been misled by temporaries that were being created and destroyed by the compiler.

Consider the following code:

1
2
3
4
5
6
7
string foo() {
    string result( "Hello World" );
    return result;
}

// ...
string hw = foo();


In the above code, with no optimizations, the compiler creates result on the stack inside foo() and then the value is "returned". Returning it in this case means that hw is assigned the returned value, possibly through operator= or the copy constructor; likely the latter) and then "result" is destroyed.

You haven't lost data; it was just transferred from one location to another.

With optimizations turned on, assuming my foo() did something more than it does, the same thing will occur. However, with optimizations turned on, your x() function is so trivial that the compiler is using an optimization technique called Return Value Optimzation (RVO) wherein the local variable (also named x) is actually constructed in the same memory location (stack location) occupied by main()'s local variable a. Which means that when x() returns, no copying is needed since there isn't really a second (temporary) instance, and therefore no destructor needs to run.

Topic archived. No new replies allowed.