c++中的const 为什么有时候会有分配空间
1. 什么情况下编译器会为其分配空间?
2. 不用extern 修饰,是否就一定不是全局变量,比如放在类,函数作用域外
[解决办法]
Normally, the C++ compiler avoids creating storage for a const , but
instead holds the definition in its symbol table. When you use
extern with const , however, you force storage to be allocated (this
is also true for certain other cases, such as taking the address of a
const ).——《Thinking in C++》
[解决办法]
1. 放在类外的,函数外的变量,是否是全局?
答:作为全局变量,一般会放在一个单独的cpp文件中,不被任何类对象所包含,在使用时,用extern声明它的存在就可以了,
2. 如果是那么 我就得问第2个问题了。
extern with const 什么意思? 是说 类外,函数外的变量和cosnt搭配的 算吗? 还是说这个关键字和const搭配?
答:extern 与const搭配,说明是个全局常量,该数据禁止被修改而已
[解决办法]
const会不会分配内存空间跟编译器的优化有关,当然,如果你强制修改const变量的值,就算优化也一定会分配空间(强制修改值的方法是取地址,然后去掉const,或者使用const_cast 丢掉const),第二个问题显然不是,声明全局变量的话不需要extern,extern只是为了引用其它文件中定义的全局变量。
[解决办法]