devxlogo

Dynamic Templated Objects

Dynamic Templated Objects

Question:
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.

Answer:
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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist