Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

c++ - Difference between static const char* and 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" );
    }
};

and

struct Obj2
{
    void Foo()
    {
        static const char* str( "hello" );
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

will print

3
2

whereas with

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

it will print

3
3

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 .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...