我明白,函数不应该返回对自动变量的引用。 但是我只是想了解常量对象的存储位置,即它是否与静态全局变量一起存储在内存段中。const对象存储在哪里
这是Visual Studio 8上的代码。它看起来像const对象存储为自动变量。我是否假设事情是正确的?或者是具体实现还是取决于构造函数是否微不足道?
如果有人能够解释为什么每个案例的行为方式都是如此,那将会非常棒。
//here i'm intentionally returning a ptr to local const ptr hope the syntax is 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;
}
wha ...没有badmotorfinger?!? – justin 2011-02-18 05:07:00
不知道我是如何错过:) – keety 2011-02-18 22:11:51