2011-02-18 45 views
0

我明白,函数不应该返回对自动变量的引用。 但是我只是想了解常量对象的存储位置,即它是否与静态全局变量一起存储在内存段中。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; 
} 
+1

wha ...没有badmotorfinger?!? – justin 2011-02-18 05:07:00

+0

不知道我是如何错过:) – keety 2011-02-18 22:11:51

回答

2

函数中分配的常量对象就像任何其他自动变量一样;他们只有const类型。全局(和类静态)变量略有不同:一些常量可以放在可执行文件的只读部分,然后只复制到内存中。这是用于像字符串和整数常量的东西;我不相信它用于任何具有不平凡构造函数的东西。

6

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 

这是一个超级简单的例子,但同样适用于被传递到功能const对象,从函数返回,或者如果函数本身是const

以下是a great article by 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 
} 
1

关于存储内容的一切都是特定于实现的。永远别忘了。有了这个警告,这里有一些典型的规则。

自动变量既可以存储在堆栈中,也可以存储在寄存器中。如果它们是const或不是无关紧要。

静态变量存储在程序存储器中。程序存储器可能有多个块,有些是只读的,有些则不是。声明变量const可能会影响存储哪些块。

分配了new的变量将位于堆上。如果它是常量或不是很重要。