When you do:
vector<string> testString(){
vector<string> result;
...
return result;
}
you create a vector result
at local scope, but just before the function gets out of scope, you return it and the critical part is that the return type of your function is vector<string>
, which copies result
and returns it to the caller of the function, which assigned it to a brand new value, in your case:
vector<string> result = testString();
but don't be confused by the same name of result
in testString()
scope and in testStringWrapper()
scope.
These two result
vector are different objects in memory. It would be equivalent with having this for example vector<string> foo = testString();
.
we should not return function local scope object to outside
True in some cases.
This applies when returning by reference or a pointer. In that case, you would have something like this:
// BAD PRACTICE
vector<string>& testString(){
vector<string> result;
...
return result;
}
and you would return a reference to an object that would go out of scope as soon as the function terminated. So when you would try to access it outside of testString()
, you would access memory that has gone out of scope.
A typical solution to this problem is to dynamically allocate memory for your object with new
, return it by reference and then manage the memory yourself (with that said, the memory will not be de-allocated until you call delete
on it).