c++ - Where are const objects stored -
i understand functions should not return references automatic variables. wanted understand constant objects stored i.e if stored in memory section along static global variables .
here code on visual studio 8 . looks const objects stored auto variables. assuming things right or implementation specific or depend on whether constructor trivial ?
would great if explain why each of these cases behave way do.
//here i'm intentionally returning ptr local const ptr hope syntax right const char* const* get_const_char_ptr() { const char * const ptr = "downontheupside"; return &ptr; } const int& get_const_int() { const int magic_number = 20; return magic_number; } const string& get_const_string() { const string str("superunknown"); return str; } const string* get_const_string_ptr() { const string str("louderthanlove"); return &str; } int main() { //case1 const int &i = get_const_int(); cout<<"case1:"<<i<<endl; //case 2 const char * const* c =get_const_char_ptr(); cout<<"case2:"<<*c<<endl; //case3 const string &str = get_const_string(); //this crashes //cout<<"case3:"<<str<<endl; return 1; }
constant objects allocated within function other automatic variable; have const
types. global (and class-static) variables different: constants can placed in read-only parts of executable file , copied memory. used things string , integer constants; not believe used nontrivial constructor.
Comments
Post a Comment