Created object on stack and then returned this object to caller. Item deleted but still there??

O

opistobranchia

blah
F test = getF();
// Print out shows that an F object was destroyed by the ~F. F set
var to 0 on delete;
test.print();
//reveals that var is still 123
value is 123 still instead of 0

F getF()
{
F f;
//default is 0;
f.setVar(123);
return f;
}

I thought since I created this on the stack instead of the heap that I
would run into problems. I have not overloaded anything. I thought
the best way would be to return a pointer to the heap and create the
object on the heap as well.

What did I miss, and why does this work? I thought that I had to do
some overloading to make data copy as well.
 
L

Larry I Smith

opistobranchia said:
blah
F test = getF();
// Print out shows that an F object was destroyed by the ~F. F set
var to 0 on delete;
test.print();
//reveals that var is still 123
value is 123 still instead of 0

F getF()
{
F f;
//default is 0;
f.setVar(123);
return f;
}

I thought since I created this on the stack instead of the heap that I
would run into problems. I have not overloaded anything. I thought
the best way would be to return a pointer to the heap and create the
object on the heap as well.

What did I miss, and why does this work? I thought that I had to do
some overloading to make data copy as well.

getF() returns an 'F' object, not a ref or pointer to an 'F', but
a full 'F' object. So, a COPY of the 'F' created inside getF() is
returned, then 'test' is initialized from that copy. The 'F' created
inside getF() is destroyed when getF() returns, but the (unnamed)
copy created from it is returned from getF(), used to init 'test', then
deleted.

Larry
 

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,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top