Newbie Q: returning objects from the freestore

S

Scott

Can you have as a return value for a function an object that has been
created on the free store? Seems like returning a pointer is the only thing
that could do this.
Thanks.
 
M

Moonlit

Hi,


Scott said:
Can you have as a return value for a function an object that has been
created on the free store? Seems like returning a pointer is the only thing
that could do this.
Nope, a reference can be used (of course internally this is the same thing
as a pointer although some people don't want you to say this).

class CObject
{
};

CObject& func()
{
return *new CObject;
}
int main()
{
CObject& Object = func();

delete &Object;

return 0;
}


But it certainly isn't good programming practice. It works but should look
like this.

class CObject
{
};

CObject* func()
{
return new CObject;
}
int main()
{
CObject *Object = func();

delete Object;

return 0;
}

And that's pointer of course.

Regards, Ron AF Greve.
 
S

Scott

Right, so the reference can be done, but isn't recommended, and the pointer
works fine in my program. But returning the object from the free store just
isn't done.

Scott
 
M

Moonlit

Hi,

Yes, you can only use a pointer (and reference), when dynamically allocated.
The other method would be to not allocate on the free store and return the
object, however then a copy is made.

CObject func()
{
CObject Object;
return Object;
}

int main()
{
CObject Object = func(); // Copies the object from the function
}

Regards, Ron AF Greve.
 
S

Scott

Thanks Moonlit:

I have better answers from you than from 3 reference works I've been pouring
through. I really appreciate the code samples as well.

Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top