本文介绍了static const char *和const char *的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下如何处理下面的两个代码段的区别?他们绝对编译到不同的汇编代码,但我试图理解代码可能会如何不同。我理解字符串字面量被抛入只读内存,并且实际上是静态的,但是与下面的显式静态有什么不同呢?

Could someone please explain the difference in how the 2 snippets of code are handled below? They definitely compile to different assembly code, but I'm trying to understand how the code might act differently. I understand that string literals are thrown into read only memory and are effectively static, but how does that differ from the explicit static below?

struct Obj1
{
    void Foo()
    {
        const char* str( "hello" );
    }
};

struct Obj2
{
    void Foo()
    {
        static const char* str( "hello" );
    }
};


推荐答案

对于静态版本,只有一个变量将被存储在某处,并且每当执行该函数时,将使用完全相同的变量。甚至对于递归调用。

With your static version there will be only one variable which will be stored somewhere and whenever the function is executed the exact same variable will be used. Even for recursive calls.

非静态版本将存储在每个函数调用的堆栈中,并在每个函数调用后销毁。

The non-static version will be stored on the stack for every function call, and destroyed after each.

现在你的例子对于编译器实际上是有点复杂,让我们先看一个更简单的例子:

Now your example is a bit complicated in regards to what the compiler actually does so let's look at a simpler case first:

void foo() {
    static long i = 4;
    --i;
    printf("%l\n", i);
}

然后一个主要的东西像这样:

And then a main something like this:

int main() {
    foo();
    foo();
    return 0;
}

将打印

3
2

>

whereas with

void foo() {
    long i = 4;
    --i;
    printf("%l\n", i);
}

它将打印

3
3

你有一个const,所以该值不能改变,所以编译器可能玩一些技巧,而它通常对代码生成没有影响,但有助于编译器检测错误。然后你有一个指针,并且记住静态对指针本身有影响,而不是它指向的值。因此,你的示例中的字符串hello很可能被放置在二进制文件的.data段中,并且只要程序存在一次就会生效,与静态事件无关。

Now with your example you have a const, so the value can't be changed so the compiler might play some tricks, while it often has no effect on the code generated, but helps the compiler to detect mistakes. And then you have a pointer, and mind that the static has effects on the pointer itself, not on the value it points to. So the string "hello" from your example will most likely be placed in the .data segment of your binary, and just once and live as long as the program lives,independent from the static thing .

这篇关于static const char *和const char *的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 11:17