静态 const char* 和 const char* 之间的区别

2022-01-12 00:00:00 string static char c++

有人能解释一下下面 2 段代码的处理方式的区别吗?它们肯定会编译成不同的汇编代码,但我试图了解代码如何表现不同.我知道字符串文字被放入只读内存并且实际上是静态的,但这与下面的显式静态有何不同?

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
", i);
}

然后是这样的主要内容:

And then a main something like this:

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

将打印

3
2

void foo() {
    long i = 4;
    --i;
    printf("%l
", 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 .

相关文章