Reputation: 813
If I create a class, and make its object inside a function*. Once the function ends what happens to the object I created? Does it get deleted?
EDIT: *And I call that function from the main
Upvotes: 0
Views: 789
Reputation: 1
"Does it get deleted?"
Yes. As long you created that object instance using automatic storage duration (sometimes referred to as stack allocation), it will be deleted as soon it goes out of scope.
struct Foo {
Foo() {}
~Foo() {}
};
void bar() {
Foo foo1; // automatic storage duration
Foo* foo2 = new Foo(); // manually-managed lifetime
} // foo1 will be deleted here, while foo2 won't
Upvotes: 2
Reputation: 1
It will get deleted as any other variable of local scope. When you create one of those they will exist until the end of the function, unless you create a pointer. In that case the data will still be there after the end of the function but you may lose the reference.
class myClass{
int variable;
float etc;
}
void foo()
{
myClass foo1 = new myClass(); // creates new instance of myClass
// as it was declared inside the function it only local scope
myClass* foo2; // it is a pointer
*foo2 = foo1; // foo2 won't be deleted. The data will still be there
// However, if you loose the reference to it,
// you may not be able to access the data stored
}
int main()
{
// foo1 still does not exist
foo(); // foo1 is created and deleted inside foo()
// main still can't "see" foo1 because of its scope
// foo2 still exists - the memory has been alocated and has a copy of
// foo1 in it, but main can't access it because it does not have the
// reference to the memory address.
}
Note that if you use another function inside the one you used to create your object, it won't be able to access it too.
Upvotes: -4
Reputation: 141554
When you declare a variable inside a block of code, then that variable has a lifetime that lasts until the end of the block of code. The variable will be destroyed when its lifetime ends, which is when control exits that block.
The proper name for this is automatic storage duration although sometimes the jargon "on the stack" is used.
If you want to keep the values in the variable then you can return a copy of the variable (don't worry, the compiler will usually optimize this).
It is also possible to create objects with manually-managed lifetime. In this scenario the objects don't have a name, you manage them via a handle, and their life doesn't end until you call delete
on their handle.
This technique requires more care and it is more complicated than using automatic variables; prefer to use automatic variables unless you really cannot solve your problem with them.
Upvotes: 5