i'm dabbling around c++ , trying wrap head around pointer thing. when creating array of objects, better create array of object type or of pointers?
for instance:
block grid[size];
or block* grid[size];
from i've been reading under impression when using objects it's better use pointers save memory? i'm going create dynamically allocated 2d array of these objects, , i'm wondering if it's worth hassling try , store them pointers in multidimensional array.
note: have been told 2d vectors, when comes dynamically creating them , allocating them i'm struggling as these arrays.
thanks in advance!
i think mixing something. classic c-array is pointer pointing first element. think of classes expensive when (deep-)copied while calling function or similar. these expensive function arguments (strings, vectors, , similar) better passed references (or pointers).
'modern c++' provides enough utility shouldnt use allocation on own, if not writing own containers. use pointers point things, not own in context. recommend not use classic c-arrays anymore. use
array<block, size> grid; // compile-time constant size
instead of
block grid[size]; // compile-time constant size
array<>
try on stack. if size
not known compile time, have allocate memory on heap. stl calls these heap-arrays vector
instead
vector<block> grid(size); // runtime variable size if (grid.size() > 0) cout << grid[0]; // use grid array
the old c-style way heap arrays allocate memory manually , free after not need anymore. error-prone , should avoided unless know do.
as mentioned difference plain old arrays (which pointers) when calling function. before had pass pointer , potentially size of array
void fancy_old_function(block* grid, size_t size) // bad practise { // things } // ... { block grid[size]; fancy_old_function(grid, size); // error prone ... // maybe alot later fancy_old_function(grid, 13); // ohoh! 13 < size? }
in c++ , big objects should pass these reference (or make pointer) otherwise vector gets deep copied.
void fancy_new_function(vector<block>& grid) // { // fancy stuff potentially change grid }
the drawback now, have different signatures dynamic , static arrays:
template <size_t n> void fancy_new_function(array<block, n>& grid) // { // fancy stuff potentially change grid }
a huge improvement classic c-arrays is, know size of array implicitly @ times.
you can call fancy_new_function
this:
{ array<block,size> grid1; fancy_new_function(grid1); // size implicitly deduced // or use grid1.size(); vector<block> grid2(size); fancy_new_function(grid2); // developer can use grid2.size() }
hth
Comments
Post a Comment