Return Local Pointer

Hey guys. I hear all the time about the rule of not returning a local pointer, but I'm not exactly sure what that insinuates.

Would this example be classified as violating that rule?

1
2
3
4
5
6
7
8
9
10
11
12
class Foo
{
public:
	Bar* ReturnBar()
	{
		Bar* temp = &bars.at(0);
		return temp;
	}

private:
	vector<Bar> bars;
};
No, that's fine.

The "don't return a local pointer" rule is this:

1
2
3
4
5
int* func()
{
    int var = 5;  // 'var' is local to func
    return &var;  // returning a pointer to local var
}


The reason this is bad is because:

1) 'var' goes out of scope when the function exits.
2) The function exits as soon as you return
3) variables that go out of scope "no longer exist"
4) A pointer to a variable that no longer exists is a bad pointer

Therefore... as soon as you return &var;, the function exits, meaning var has gone out of scope, meaning the pointer you returned immediately becomes a bad pointer.



Your example with a class is fine because you're getting a pointer to an element in a vector. That vector will exist (and the pointer will be valid) for as long as the object instance is valid:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// using your 'Foo' class example:
void example()
{
    Bar* ptr;

    {  // braces to limit scope
        Foo foo;

        ptr = foo.ReturnBar();

        // here, 'ptr' is OK to use because it points to foo.bars[0], which is [presumably]
        //  a valid object.

    }  // <- 'foo' goes out of scope here

    // here, 'ptr' is now a bad pointer because the object it points to no longer exists
    //   (it went away when 'foo' was destructed... which is when foo went out of scope
    //   on the above closing brace)
}
No. Well, kinda, if the Foo object goes out of scope after the function ReturnBar() is called.

1
2
3
4
5
int* Bad()
{
   int LocalObject;
   return &LocalObject;
};


Since LocalObject is local to the function Bad, as soon as the function returns LocalObject no longer exists, and so the pointer that points to LocalObject is not valid, resulting in a segmentation fault, because the memory has been released.
Thanks guys! Great help. :)
Topic archived. No new replies allowed.