const对象存储在哪里

时间:2011-02-18 04:42:15

标签: c++ reference 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;
}

3 个答案:

答案 0 :(得分: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 :(得分:2)

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

答案 2 :(得分:1)

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

自动变量存储在堆栈或寄存器中。如果它们是常数也无关紧要。

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

使用new分配的变量将在堆上。如果它是常量也没关系。