-
March 17th, 2009, 10:18 PM
#1
Local object can be reference outside function
I need help explaining me the below code. my function called "getPerson" create a temporary object and return the object's address to the calling function. from the calling function, I want to know why i can still use that address to reference it's class member.
Talking about scope and object lifetime, the temporary object would be destroyed on function return, and subsequent reference to that object would result in null pointer.
But when i compile and run the program, the above rule is not true. so it seems that the object in memory is not immediately removed.
Code:
#include <iostream>
using namespace std;
class Person{
public:
int age;
~Person(){cout<<"Class ending..."<<endl;}
};
Person *getPerson(){
Person p;
p.age=10;
return &p;
}
int main(){
Person *p;
p=getPerson();
cout<<p->age<<endl;
getchar();
return 0;
}
-
March 17th, 2009, 11:32 PM
#2
Re: Local object can be reference outside function
Originally Posted by piggy181
Talking about scope and object lifetime, the temporary object would be destroyed on function return, and subsequent reference to that object would result in null pointer.
The local variable will be destroyed when the return returns, but the pointer returned is not a null pointer, but rather a pointer that points to a destroyed object. Dereferencing such a pointer results in undefined behaviour.
-
March 18th, 2009, 02:16 AM
#3
Re: Local object can be reference outside function
Talking about scope and object lifetime, the temporary object would be destroyed on function return, and subsequent reference to that object would result in null pointer.
Nope. Pointers are never set to NULL automatically. Pointers are just a memory address. That never becomes 0. But the object/value stored at that address becomes invalid. So, never do what you did in getPerson().
-
March 18th, 2009, 09:41 AM
#4
Re: Local object can be reference outside function
The object 'p' is created as a local object in the getPerson() function. Therefore when this function returns it is no longer safe to access this object, even though you have a pointer to where it used to be.
If you do try to access it, the behaviour is undefined and thus anything could happen. One of these possibilities is of course that the contents of the memory has not been changed and therefore accessing p->age will give you the value 10 - as you are probably seeing.
This is just luck, however, and you should never try to access objects which no longer exist.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|