I have a class called Object which stores some data.
I would like to return it by reference using a function like this:
Object& return_Object();
Then, in my code, I would call it like this:
Object myObject = return_Object();
I have written code like this and it compiles. However, when I run the code, I consistently get a seg fault. What is the proper way to return a class object by reference?
You can only use
if the object returned has a greater scope than the function. For example, you can use it if you have a class where it is encapsulated. If you create an object in your function, use pointers. If you want to modify an existing object, pass it as an argument.
Well, it is maybe not a really beautiful solution in the code, but it is really beautiful in the interface of your function. And it is also very efficient. It is ideal if the second is more important for you (for example, you are developing a library).
The trick is this:
A a = b.make();
is internally converted to a constructor of A, i.e. as if you had writtenA a(b.make());
.b.make()
should result a new class, with a callback function.Here is my minimal example. Check only the
main()
, as you can see it is simple. The internals aren't.From the viewpoint of the speed: the size of a
Factory::Mediator
class is only 2 pointers, which is more that 1 but not more. And this is the only object in the whole thing which is transferred by value.You can only return non-local objects by reference. The destructor may have invalidated some internal pointer, or whatever.
Don't be afraid of returning values -- it's fast!
You're probably returning an object that's on the stack. That is,
return_Object()
probably looks like this:If this is what you're doing, you're out of luck -
object_to_return
has gone out of scope and been destructed at the end ofreturn_Object
, somyObject
refers to a non-existent object. You either need to return by value, or return anObject
declared in a wider scope ornew
ed onto the heap.I will show you some examples:
First example, do not return local scope object, for example:
you can't return ret by reference, because ret is destructed at the end.
Second example, you can return by reference:
you can return by reference for both s1 and s2 is still existing.
Third example:
usage code as below:
because after return by reference the object is still exists;
Fourth example
usage example:
Fifth example: