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)
}
|