How to “return an object” in C++?

I know the title sounds familiar as there are many similar questions, but I’m asking for a different aspect of the problem (I know the difference between having things on the stack and putting them on the heap).

In Java I can always return references to “local” objects

public Thing calculateThing() {
    Thing thing = new Thing();
    // do calculations and modify thing
    return thing;
}

In C++, to do something similar I have 2 options

(1) I can use references whenever I need to “return” an object

void calculateThing(Thing& thing) {
    // do calculations and modify thing
}

Then use it like this

Thing thing;
calculateThing(thing);

(2) Or I can return a pointer to a dynamically allocated object

Thing* calculateThing() {
    Thing* thing(new Thing());
    // do calculations and modify thing
    return thing;
}

Then use it like this

Thing* thing = calculateThing();
delete thing;

Using the first approach I won’t have to free memory manually, but to me it makes the code difficult to read. The problem with the second approach is, I’ll have to remember to delete thing;, which doesn’t look quite nice. I don’t want to return a copied value because it’s inefficient (I think), so here come the questions

  • Is there a third solution (that doesn’t require copying the value)?
  • Is there any problem if I stick to the first solution?
  • When and why should I use the second solution?

8 Answers
8

Leave a Comment