Fork me on GitHub

6/26/2011

[C++] local variable 為什麼可以離開 scope 而被存取

在 stackoverflow 看到一則有趣的討論串,問題是這樣的:

int * foo()
{
    int a = 5;
    return &a;
}

int main()
{
    int* p = foo();
    cout << *p;
    *p = 8;
    cout << *p;
}

And the code is just running with no runtime exceptions! The output was 5 8! How can it be? Isn't the memory of a local variable inaccessible outside its function?

意思就是為什麼 a 這個函數的局部變數還存活到離開了函數的 scope 呢?下面一個答案的比喻真是妙極了:
You rent a hotel room. You put a book in the top drawer of the bedside table and go to sleep. You check out the next morning, but "forget" to give back your key. You steal the key!

A week later, you return to the hotel, do not check in, sneak into your old room with your stolen key, and look in the drawer. Your book is still there. Astonishing!

How can that be? Isn't the contents of a hotel room drawer inaccessible if you haven't rented the room?

這個作者回答的相當生動,當然後面也補充了一些技術細節,有興趣的可以到這裡參考!

參考文章


... ...

No comments:

Post a Comment