zoukankan      html  css  js  c++  java
  • [C++再学习系列] 具有链接的C++实体

    具有链接的实体,包括名字空间级的变量和函数,都是需要分配内存的。具有链接的实体如果在源文件(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变量。

    注:个人理解:何为具有链接的实体呢?通常而言,变量和函数的定义即是。

    变量和函数定义的讨论,详见:http://www.cnblogs.com/zhenjing/archive/2010/10/12/1848691.html

  • 相关阅读:
    从 HTTP 到 HTTPS
    一条很用的MSSQL语句
    MVC中 jquery validate 不用submit方式验证表单或单个元素
    深信服务发布SSL站点
    警告: 程序集绑定日志记录被关闭(IIS7 64位系统)
    Winform中子线程访问界面控件时被阻塞解决方案
    C# Winform中执行post操作并获取返回的XML类型的数据
    vs2010 vs2012中增加JSon的支持
    WebService应用一例,带有安全验证
    C#事件、委托简单示例
  • 原文地址:https://www.cnblogs.com/zhenjing/p/1851573.html
Copyright © 2011-2022 走看看