Difference between static const char* and const char*(静态 const char* 和 const char* 之间的区别)
问题描述
有人能解释一下下面 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 .
这篇关于静态 const char* 和 const char* 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:静态 const char* 和 const char* 之间的区别
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- C++ 协变模板 2021-01-01