I am currently trying to get into writing proper C++ code (getting it running was ok for some small prototypes, but it's been ugly).
I recently realized the difference of heap and stack instantiation (O m = new O() vs. O m()).
Now I have a class, where the header file defines a variable, which holds an table definition.
ChunkLoader.hpp:
TablePartion *tablePartial_;
ChunkLoader.cpp:
ChunkLoader() { tablePartial_ = new TablePartial(true, 0, 1); }
Now I want to instantiate the tablePartial on the stack, but I cannot use:
TablePartial tablePartial_(true, 0, 1);
I am totally blind? How can I allocate tablePartial_ on the stack?
Or I am getting it totally wrong, and I cannot use in the constructor since it would be out of scope after the constructor and thus be freed? But since I read that stack variables are better performance-wise, I'd like to use stack instantiation (and getting red of delete
).
Main reason: stack overflow told me to get rid of pointers when ever possible. :)
To start off, you should probably avoid the terms "on the stack" or "on the heap", they're implementation details that have nothing to do with the concepts being discussed. Instead, we discuss the lifetime of the object, in terms of automatic
(which more or less correlates with the stack), dynamic
(which more or less correlates with the heap), static
(which more or less correlates with globals), and thread
(which is a thread-specific global).
In answer to your specific question, you can use constructor initializers to initialize your variable:
ChunkLoader()
: tablePartial_(true, 0, 1)
{
}