I’m curious, what is a difference between:
Trie* trie = new Trie();
and
Trie trie;
I guess that whereas in the first case trie is just a pointer to the object in the second case trie is the object itself. But what is the difference in practice? When to use which way?
Or, is some on these a “preferred” style?
This shows you need to start learning C++ seriously from a book. The answer to this question will be very long as these two are very different.
In short however, these are some clues for you:
Allocates memory on the heap, you get a pointer to the allocated memory and you need to
deleteit when you are done with it.Allocates
trieon stack and the object is destroyed as soon as its scope ends.You use the first one if you need an object to be alive through different scopes, and the second if the object is only needed in a specific scope.
The first one has run time cost while the second one has none (or very very little).
With the first one, you can allocate all the memory you want (as much RAM as you have), while with the second you are bound by the size of the stack.
Edit: Answer to your first comment
The stack is allocated by the operating system when the program is loaded. The compiler does not assume any particular size for the stack and indeed, upon every function call or in general when you enter e new scope, simply goes and writes further on the stack. If you have recursive functions that go too deep, indeed you will get a segmentation fault (access violation) error.
Heap on the other hand is the whole pool of memory the computer had, and the operating system manages. A call to
newrequests memory from the operating system. If there is not enough memory, the operating system may reject the request and you will get aNULL(Side note: after everynewyou must check whether the result isNULLor not. If it isNULL, you should handle this failing case. Otherwise your program will crash). Likewise, when don’t need the memory again, you mustdeleteit. Note also thatdeletecalls the destructor of your object and thus is in fact crucial for a sane program.