Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I can't find where in the standard that it says this program is undefined:

#include <iostream>

int main() 
{
    int *p;
    {
        int n = 45;
        p = &n;
    }
    std::cout << *p;
}

None of the cases in §3.8 object lifetime seem to apply here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
321 views
Welcome To Ask or Share your Answers For Others

1 Answer

I'm not 100% sure because of the wording but it looks like this is covered by 3.8/6 (the reason I think this interpretation is correct is because of the non-normative example in 3.8/5, // undefined behavior, lifetime of *pb has ended):

...after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways....The program has undefined behavior if:

Then the first bullet is the culprit: an lvalue-to-rvalue conversion (4.1) is applied to such a glvalue,: This conversion has to happen either at the point of call to operator<< or finally at the point where the integral value is read for formatting within ostream code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...