Memory allocation at compile time

Consider the following piece of code:

#include  /* C++ String class */static String s(“hello”);main() {  // … your code  s += ” world”; // …}
Question: String class uses the new operator to allocate space for the char string argument in the constructor. Where exactly is space allocated for the static string s? If new allocates only heap memory, then s is on the heap. This implies that heap memory can be allocated at compile time. Correct?

Nice try but no cigar.

Static initialization has two phases: a static phase that is resolvedat compile time, and a dynamic phase that happens at run time.

At the static phase, all statics and globals that are initialized withconstant expressions are evaluated; all other things (calls to constructors, initialization with calls to functions including operator new, etc.) are dealt with at run time. These can be initialized either before the callto main or sometime later before any function in the module(file) in whichthey are defined is called.

So at compile time, the compiler only generates code to call the constructorto string at the appropriate place.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: