returning a local object reference alternative

Started by
7 comments, last by Oluseyi 19 years, 10 months ago
Say I have a two classes LoveHugeStuff and HugeClass now.. (syntax might be screwed, it is only an example)

HugeClass& LoveHugeStuff::giveBigStuff() {
  HugeClass hc;
  hc.doStuffThatMakeMeHuge();
  return hc
}
That obviously won''t work since by the time the reference is used, the local object has been destroyed. On the other hand, returning the whole object isn''t really an option since it''ll make it huge. I could have LoveHugeStuff maintain the copy of HugeClass until the function is called again.. but it wouldn''t be too practical either. Any advice ?
I teleported home one night; With Ron and Sid and Meg; Ron stole Meggie's heart away; And I got Sydney's leg. <> I'm blogging, emo style
Advertisement
You can either create it on the heap and return a pointer (thus forcing the client to free it), or use a smart pointer.
void A::f(Z &z){  z.h();}Z *A::g(){  Z *z = new Z();  z->h();  return z;}
Although i do not understand what your exactly trying to accomplish, but perhaps you could use the return optimization. (assuming C++, not sure if this will work in other languages)

class HugeClass{public:    HugeClass(){        // this constructor does something that will make it huge    }};HugeClass giveBigStuff(){    return HugeClass();}


This looks very similar to:
HugeClass hc();
return hc;

But the compiler will optimize the first mentioned method.
When it sees syntax such as: return HugeClass(); it will build the object directly in the location of the outside return value. This means that no tempory object has to be contructed in the function and as a consequence the object doesn''t have to be copied. Thus saving a copy-constructor call as well as a destructor call.
quote:Original post by Direct4D
This looks very similar to:
HugeClass hc();
return hc;

But the compiler will optimize the first mentioned method.
A good compiler will optimise the second method, too.
I just realized that the second method does not work.

It treats:
HugeClass hc();
as an function prototype.

So i should have written:
HugeClass hc;
return hc;



btw: just tested if my compiler (Borland Builder 6) would do the optimize you mentioned...
It won''t. (compiled as release build with all optimization options on)
Quote:Original post by Coriiander
Even auto_ptr destroys the object when the function goes out of scope.
It shouldn't. That's waht its designed for.

show us the code you tried.
Alternative solution:

void LoveHugeStuff::giveBigStuff(HugeClass *hc) {  // Store a private pointer to hc  hc->doStuffThatMakeMeHuge();}


IOW, the caller is responsible for constructing HugeClass.
神はサイコロを振らない!
void LoveHugeStuff::giveBigStuff(HugeClass *& hc) {  hc = new HugeClass;  hc->doStuffThatMakesMeHuge();}

This topic is closed to new replies.

Advertisement