Obviously, you wouldn't want to have a
delete in the
buildTree() function. The whole point of the function is to create the tree and hand it back to the calling code, and if you deleted the memory you've just allocated, then you'd be destroying the very thing you were supposed to be creating.
Somewhere else in the program, there should be some code responsible for calling
delete to free up the memory used by the tree, after it's no longer required. Possibly, you should create a destructor for
node, and do it there.
If I continue to run the code repeatedly, will my computer's RAM get full? |
That part of the RAM set aside for processes to use would fill up, yes. On any sensible operating system, though, that won't be
all the computer's RAM, just a part of it. At that point,
new will start throwing an exception, and what happens then depends on what the calling code does with that exception.
And in any case, the
node class is pretty small; you'd have to create an awful lot of them to fill up the available memory. It's unlikely to happen unless you're deliberately trying to do it.
Instead of using "new" keyword in the function, what would you guys use? |
In modern C++, it's better to use the appropriate smart pointer, to reflect the ownership of the memory. I'm guessing here, that would be
std::unique_ptr . Then, instead of
new, you would use
std::make_unique().