Hi,
There are differences between Go and C++, I can't help thinking that porting a Go program to C++ may not be be the best way to learn C++.
Go has Garbage Collection for memory management, for which it uses the
new
function to allocate memory. C++ does not have GC, and using
new
means one is doing manual memory management with pointers, which are two bad things for a beginner. Even though
new
does very similar but subtly different things in Go and C++, it means that the wrong approach is followed in C++. The problem with new is that if something throws an exception, neither the destructor nor the
delete
are reached and memory is leaked. So that is why we prefer to use an STL container which does it own memory management very efficiently.
Instead consider using STL containers which manage memory themselves. For such a small amount of data as this is likely to be you could get away with a plain 2D array on the stack. But it is better to use a container that implicitly puts it's data on the heap. So try this, it's a square 2D std::array:
1 2
|
constexpr std::size_t Size {10};
std::array<std::array<Tile,Size>, Size> TheMap;
|
Or if you want to use a 1D representation of a 2D array, try
std::vector
Some other topics to research:
References: One can't have a container of references, but there is
std::reference_wrapper
. Elsewhere references are a good thing, they behave like pointers. Use them for anything which is not a builtin type, unless you are going to use std::move
Smart pointers:
std::unique_ptr
and
std::shared_ptr
these embody the RAII concept.
Do try to get rid of your global variables, make the scope of variables as small as possible.
Good Luck !!