How does the compiler handle dynamically allocated templated objects? As I have read, the compiler generates code for templated objects and functions according to the required data type.
A template class specialization (i.e., a template instance) is defined at compile time. Its code is generated on demand. For example:
std::vector vi; // generate a vector of int
The compiler isn't responsible for dynamic allocation; it's the runtime environment (usually the OS kernel) that handles the allocation request at runtime, when operator new (or new for arrays) is invoked. Thus, when programmers allocate a template object, they allocate an object that already exists; the code for the template instance is generated at compile time, before the allocation takes place. In other words, allocating a template instance is just like allocating any other object.