设为首页 加入收藏

TOP

2.9.1 Designing Our Own Headers (2)
2013-10-07 15:23:56 来源: 作者: 【 】 浏览:61
Tags:2.9.1 Designing Our Own Headers

Some const Objects Are Defined in Headers

Recall that by default a const variable (Section 2.4, p. 57) is local to the file in which it is defined. As we shall now see, the reason for this default is to allow const variables to be defined in header files.

In C++(www.cppentry.com) there are places where constant expression (Section 2.7, p. 62) is required. For example, the initializer of an enumerator must be a constant expression. We’ll see other cases that require constant expressions in later chapters.

Generally speaking, a constant expression is an expression that the compiler can eva luate at compile-time. A const variable of integral type may be a constant expression when it is itself initialized from a constant expression. However, for the const to be a constant expression, the initializer must be visible to the compiler. To allow multiple files to use the same constant value, the const and its initializer must be visible in each file. Tomake the initializer visible, we normally define such consts inside a header file. That way the compiler can see the initializer whenever the const is used.

However, there can be only one definition (Section 2.3.5, p. 52) for any variable in a C++(www.cppentry.com) program. A definition allocates storage; all uses of the variablemust refer to the same storage. Because, by default, const objects are local to the file inwhich they are defined, it is legal to put their definition in a header file.

There is one important implication of this behavior. Whenwe define a const in a header file, every source file that includes that header has its own const variable with the same name and value.

When the const is initialized by a constant expression, then we are guaranteed that all the variables will have the same value. Moreover, in practice,most compilers will replace any use of such const variables by their corresponding constant expression at compile time. So, in practice, there won’t be any storage used to hold const variables that are initialized by constant expressions.

When a const is initialized by a value that is not a constant expression, then it should not be defined in header file. Instead, as with any other variable, the const should be defined and initialized in a source file. An extern declaration for that const should be made in the header, enabling multiple files to share that variable.

例如英文原版书第58 页的例子,以fcn() 函数调用的返回值来初始化const intbufSize,那么应该把初始化放到.cc 文件中,以避免fcn() 被反复调用。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇2.3.2 The Name of a Variable 下一篇2.9.1 Designing Our Own Headers..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·进入Linux世界大门的 (2025-12-24 14:51:47)
·Download Linux | Li (2025-12-24 14:51:44)
·Linux 指令初探:开 (2025-12-24 14:51:41)
·TCP连接失败的原因与 (2025-12-24 14:19:27)
·TCP Sever模式与TCP (2025-12-24 14:19:24)