Reputation: 1636
I am not sure what is wrong with this (keep in mind I'm kinda sorta new to C++)
I have this class:
Foo
{
string name;
public:
SetName(string);
}
string Foo::SetName(string name)
{
this->name = name;
return this->name;
};
//////////////////////////////////////////////
//This is where I am trying to return a Foo pointer from this global function:
Foo * ReturnFooPointer()
{
Foo foo;
Foo * foo_ptr;
foo_ptr = &foo;
return foo_ptr;
}
At compile time, this compiles just fine. However at run time it throws a runtime exception(Some sort of access violation)
What am I doing wrong?
Upvotes: 22
Views: 55799
Reputation: 7895
the actual object is allocated on the stack so it is destroyed when it goes out of scope (when the function returns). If you allocate it on the heap (with new
), it will be alive until you delete
it
Upvotes: 3
Reputation: 55445
You're returning a pointer to a local object on the stack. It goes out of scope the moment your function returns, and is invalid.
You should create a new instance to return, i.e.,
Foo* foo_ptr = new Foo();
This will create an object in the heap and will live until you call delete
on it.
Upvotes: 8
Reputation: 347586
You need to use the new keyword instead to create new Foo on the heap.
The object on the stack will be freed when the function ends, so you are returning a pointer to an invalid place in memory.
Here is the correct code.
Foo * ReturnFooPointer()
{
Foo * foo_ptr = new Foo();
return foo_ptr;
}
Remember later to delete the pointer you are returning.
So later in code:
Foo *pFoo = ReturnFooPointer();
//Use pFoo
//...
delete pFoo;
Upvotes: 40