I’ve looked around trying to figure out if I should return a 2D array in C++, but got mixed answers.
Some of the answers say no because the data is local to the function and when it returns, the array points to “junk data” (as it can be overwritten at any time). However, some said “yes, return it like a normal array.”
So, to my dilemma:
I have a 2D array that holds pointers to Tile objects
Tile* map[128][128];
Should I return the array in a function? Why or why not? If the answer is yes, how would I do that?
EDIT: I was unclear. I want to make a getter method to return the map variable and be able to use the pointers in the array in another function.
You could do that… the problem is that your caller is now responsible for freeing the memory. And he might not know how you allocated it. Should he call free()? delete[]? A free routine provided by the OS? Or one provided by some other memory caching system in your app?
Two common ways around this are:
But then… who’s going to free the Tile* instances? And with what API? So perhaps you need a vector of vectors of Tile, rather than Tile*.