Quote:Original post by nibbuler
Ahh... just checked out the scope of variables at cplusplus.com. I thought that I could treat anything I defined as a pointer as a global variable--big mistake (didn't know they would be deleted when the function ended).
I'm guessing you are probably getting confused with pointers and allocated memory.
void f(){ int *i=new int[200];}
After f() exits, the memory allocated still exists, but the pointer i is deleted, so you have no way of accessing the memory or freeing it.
int *f(){ int *i=new int[200]; return i;}void g(){ int *ptr=f(); // do stuff delete [] ptr;}
Here you are returning a copy of i before it is destroyed, so you can access the memory.
However, all of the above are typical examples of the potential problems with using pointers directly in C++ and why you should almost always prefer to use standard library containers or smart pointers instead.
std::vector<int> f(){ return std::vector<int>(200);}void g(){ std::vector<int> v=f(); // do stuff}
The above is very hard to break, and is unlikely to have any significant performance penalties. Even the apparent additional copy of the vector when being returned is likely to be optimised away by the compiler.