kee*_*ety 0 c++ const reference
我明白函数不应该返回对自动变量的引用.但是我只想了解常量对象的存储位置,即它是否与静态全局变量一起存储在内存部分中.
这是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;
}
Run Code Online (Sandbox Code Playgroud)
const不会改变存储内容的地方,它是一个关键字,告诉编译器阻止变量或函数修改内容.例:
std::string myNormalStr("Hello");
const std::string myConstStr("Don't Change Me");
myNormalStr = myConstStr; // this is ok
myConstStr = myNormalStr; // this will give you a compile error
Run Code Online (Sandbox Code Playgroud)
这是一个超级简单的例子,但同样的事情适用于const传递给函数,从函数返回或函数本身的对象const.
这是Herb Sutter关于使用const关键字的所有正确方法的精彩文章.
编辑:
目前几乎没有理由使用该auto关键字,因为在其范围内所有内容都是隐式自动的.此关键字是自动变量的存储类说明符.
但是,auto关键字正在作为正在进行的新C++标准的一部分进行更改,但Visual Studio 2010和其他一些编译器已经支持它新的辉煌形式.它可以像C++ 0x一样使用:
std::vector<int> numbers;
for (std::vector<int>::const_iterator itr(numbers.begin());
itr != numbers.end(); ++itr)
{
// do something with each iterated element
}
// compiler auto deduces from rvalue
// and determines that you want a
// std::vector<int>::const_iterator type
for (auto itr = numbers.cbegin();
itr != numbers.cend(); ++itr)
{
// do something with each iterated element
}
Run Code Online (Sandbox Code Playgroud)