C ++: pointers and scope

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

Will the result testbe a bad pointer? As far as I know, a should be deleted and then bbecome a confused pointer, right?

What about more complex things, not an int pointer, but the same with a class with 20 members or so?

+5
source share
4 answers

The term for what you return is a dangling pointer . " aIs a local variable allocated on the stack and it is no longer available when it leaves the scope (which is no different from garbage collection). Attempting to use the result of the call test()will be undefined .

, a - (int *a = new int(5);), int *b = a; return b; , , return new int(5). , free , .

+7

, , , a. , int, , . ++ .

, , , , :

int test( )
{
    int a = 5;
    return a;
}

, .

+5

b , . , .

, , , malloc() new, , free delete .

+2

, . , , . -, , -, , - . - , , . , , .

, , , , , - ( ) , .

, , "" , . , - , . , , , . ++ , - AT & T, shared_ptr. , , , .

0
source

All Articles