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* 之间的区别
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01