[C++再学习系列] 具有链接的C++实体
2009-07-11 17:13
363 查看
具有链接的实体,包括名字空间级的变量和函数
,都是需要分配内存的。具有链接的实体如果在源文件
(cpp)
中出现多次,将意味着多次分配内存,每个内存空间定义一个特定的实体。这会导致
:1)
空间膨胀;
2)
出现多个变量,变量的状态不共享。
因此,不能将下面的代码放在头文件:
// avoid defining entities with external linkage in a header
int fudgeFactor;
std::string hello("Hello, world!");
void foo() {/* … */}
上述的全局变量和函数定义,在该头文件被多个源文件包含时,将导致连接错误,编译器将报告存在名字重复。
问题的解决方案:
//put just the declarations in the header:
extern int fudgeFactor;
extern string hello;
void foo();
//
"extern" is optional with function declarations
//The actual definitions go in a single implementation file:
int fudgeFactor;
string hello("Hello, world!");
void foo() {/* … */ }
更应该注意的是
static
的头文件链接实体:
// avoid defining entities with static linkage in a header
static int fudgeFactor;
static string hello("Hello, world!");
static void foo() {/* … */ }
C++
中,
static
数据和函数的重复是合法的。编译器将
static
对象解释成:每个文件都有一个私有副本
(static
的作用域是文件
)
。这意味着编译器不会报错,这样会导致每个文件都拥有自己的独立副本。故要慎用
static
变量。
,都是需要分配内存的。具有链接的实体如果在源文件
(cpp)
中出现多次,将意味着多次分配内存,每个内存空间定义一个特定的实体。这会导致
:1)
空间膨胀;
2)
出现多个变量,变量的状态不共享。
因此,不能将下面的代码放在头文件:
// avoid defining entities with external linkage in a header
int fudgeFactor;
std::string hello("Hello, world!");
void foo() {/* … */}
上述的全局变量和函数定义,在该头文件被多个源文件包含时,将导致连接错误,编译器将报告存在名字重复。
问题的解决方案:
//put just the declarations in the header:
extern int fudgeFactor;
extern string hello;
void foo();
//
"extern" is optional with function declarations
//The actual definitions go in a single implementation file:
int fudgeFactor;
string hello("Hello, world!");
void foo() {/* … */ }
更应该注意的是
static
的头文件链接实体:
// avoid defining entities with static linkage in a header
static int fudgeFactor;
static string hello("Hello, world!");
static void foo() {/* … */ }
C++
中,
static
数据和函数的重复是合法的。编译器将
static
对象解释成:每个文件都有一个私有副本
(static
的作用域是文件
)
。这意味着编译器不会报错,这样会导致每个文件都拥有自己的独立副本。故要慎用
static
变量。
相关文章推荐
- [C++再学习系列] 具有链接的C++实体
- [C++再学习系列] 具有链接的C++实体
- 具有链接的C++实体
- 具有链接的C++实体
- [C++再学习系列] 可访问性问题
- [C++再学习系列] 深入new/delete:Operator new的全局重载
- C++ 学习笔记(19)new/delete表达式、定位new、typeid、dynamic_cast、type_info、枚举类型、成员函数指针、union、位域、volatile限定符、链接指示
- 【面向对象语言系列】关于C++深度学习,你需要知道的事
- C/C++、VC/MFC、嵌入式、Java/XML、数据库/多线程/网络/图形/数据结构/数学”系列学习精粹
- C++学习系列(四)——String使用
- [C++再学习系列] 二元操作符重载
- 学习C++:实践者的方法(Beta1)-刘未鹏编程语言系列
- 总结系列_4(C++知识学习,续...)
- [C++再学习系列] 隐式类型转换与转换操作符
- [C++再学习系列] 析构函数不能失败的理由
- [C++再学习系列] 函数声明与STL容器构造
- C++学习链接
- [C++再学习系列] ADL(Koenig)查找
- [C++再学习系列] 引用和指针
- 【C++】学习笔记草稿版系列7(命名空间)