Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Jul 18, 1997

Memory allocation at compile time

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

Answer:
Nice try but no cigar.

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

At the static phase, all statics and globals that are initialized with constant 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 call to main or sometime later before any function in the module(file) in which they are defined is called.

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

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date