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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date