const 对象存储在哪里

发布于 2024-10-17 17:44:32 字数 1099 浏览 1 评论 0原文

我确实理解函数不应返回对自动变量的引用。 然而我只是想了解常量对象存储在哪里,即它是否与静态全局变量一起存储在内存部分中。

这是 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;
}

I do understand that functions should not return references to automatic variables.
However I just wanted to understand where constant objects are stored i.e if it is stored in the memory section along with static global variables .

Here is the code on Visual studio 8 . It looks like const objects are stored as auto variables. Am i assuming things right or is it implementation specific or does it depend on whether the constructor is trivial ?

Would be really great if someone could explain why each of these cases behave the way they do.

//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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

红颜悴 2024-10-24 17:44:32

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 的情况。

这是 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
}

const does not change where things are stored it's a keyword to tell the compiler to prevent variables or functions from modifying things. Example:

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

That's a super simplistic example but the same thing applies to const objects which are passed into functions, returned from functions, or if the function itself is const.

Here's a great article by Herb Sutter on all the correct ways to use the const keyword.

Edit:

Currently there is almost no reason to use the auto keyword as everything is implicitly auto within it's scope. This keyword is a storage class specifier for an automatic variable.

However the auto keyword is changing as part of the new C++ standard in progress but is supported already by Visual Studio 2010 and some other compilers in it's new glorious form. It can be used like so in 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
}
爱情眠于流年 2024-10-24 17:44:32

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

Constant objects allocated within a function are just like any other automatic variable; they just have const types. Global (and class-static) variables are slightly different: some constants can be placed in read-only parts of the executable file and then just copied into memory. That is used for things like string and integer constants; I do not believe it is used for anything with a nontrivial constructor.

盗梦空间 2024-10-24 17:44:32

绝对,关于存储内容的所有内容都是特定于实现的。永远不要忘记这一点。带着这个警告,这里有一些典型的规则。

自动变量要么存储在堆栈中,要么存储在寄存器中。它们是否 const 并不重要。

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

使用 new 分配的变量将位于堆上。无论它是否为 const 都没有关系。

Absolutely everything about where something is stored is implementation specific. Never forget that. With that caveat, here are some typical rules.

Automatic variables are either stored on the stack or in a register. Doesn't matter if they're const or not.

Static variables are stored in program memory. There may be multiple blocks of program memory, some read-only and some not. Declaring a variable const may affect which block something is stored in.

Variables allocated with new will be on the heap. Doesn't matter if it's const or not.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文