C++ Primer : Memory Models and Namespaces [Progress Check]

本文深入探讨C++中的内存模型和命名空间。讲解了分离编译程序的概念,详细阐述了存储持续时间、作用域和链接性,包括自动存储持续时间、静态存储变量(外部和内部链接),以及动态分配。此外,还介绍了如何创建命名空间和使用声明及指令。
摘要由CSDN通过智能技术生成

Memory Models and Namespaces

Separate Compilation of Programs

  • C++ allows and encourages you to locate component functions of a program in separate files.
  • Compile files separately and then link them into the final executable program.
  • header files:
    • function prototypes
    • symbolic constants defined using #define or const
    • structure declarations: no variables created
    • class declaration
    • template declaration
    • inline function
  • How to include header file ?
    • use "coordin.h"
    • NOT use <coordin.h>
    • < >: C++ looks at system’s file system
    • " ": C++ first looks at current working directory or source code director, after that, looks at system’s file.
  • Example of header file
#ifndef COORDIN_H_ // avoid multiple define
#define COORDIN_H_
...

#endif

Storage duration, Scope, and Linkage

Storage Duration

  • Storage categories affect how information can be shared across files.
  • C++ has 4 separate schemes for storing data:
    • Automatic storage duration:
      • Variables declared inside a function definition.
      • Created when program execution enters the function or block.
      • Freed from memory when execution leaves the function or block.
    • Static storage duration:
      • Variables defined outside a function definition or using the keyword static.
      • Persist for the entire time a program is running.
    • Thread storage duration(under C++ 11):
      • Variables declared with the keyword thread_local.
      • Concurrent programming.
    • Dynamic storage duration:
      • Memory allocated by the new operator persists until freed with delete operator or the program ends, whichever comes first.

Scope and Linkage

Automatic Storage Duration
  • Function parameters and variables declared inside a function have automatic storage duration by default.
  • Automatic storage duration means variables can only be seen inside a block or function.
    • variables with the same name, the new definition inside the block will hide the prior definition.
    • prior definition comes out after block or function ends.
int main()
{
    int a = 5; 
    {
        int b = 6; // b only valid in the block
        int a = 7; // a is 7 inside the block
    }
    ... // a is 5 and b does not exist
    ...
    return 0
}
  • To manage automatic variables, C++ uses the Stack, following last-in-first-out
Static Duration Variables
  • Three types:
    • external linkage
    int global = 100;
    
    • internal linkage
    static int one_file = 10;
    
    • no linkage
    void func1(int n)
    {
        static int count = 0;
    }
    
  • Notes:
    • global can be used in this file and other linked files.
    • one_file can only be used in this file.
    • count is defined inside the block and only used by func1. It is like automatic variables but it lasts in the memory longer.
  • All types of static duration variables last for the entire duration of the program.
  • Compiler does not need any special tools to manage static duration variables and just to use a fixed block of memory to hold all of them. If no explicit declaration, the compiler sets it to 0.
  • Initialization: zero-initialization by default.
#include <cmath>
int x; // zero-init
int y=5; // constant-expression init
long z=13*13; // constant-expression init
int w = 2 * sizeof(long) +1; // constant-expression init
const double pi = 4.0 * atan(1.0); // dynamic init, because of callin atan()
Static Duration, External Linkage
  • External Variable:
    • variables with external linkage.
    • defined above main() function or in header file.
    • also called global variable, compared with automatic variables (local variable)
  • One Definition Rule
    • there can be only one definition of a variable.
      • defining declaration
        • it causes storage for the variable to be allocated.
      • referencing declaration
        • not cause storage to be allocated and only refers to an existing variable.
    • referencing declaration: extern:
    double up;  // definition, up is 0
    extern int blem;  // blem is defined elsewhere.
    extern char gr = 'z';  // definition (initialized)
    
Static Duration, Internal Linkage
  • static modifier: file-scope variable with internal linkage.
// file 1
int error = 20; // external declaration

// file 2
static int error = 5; // known only in file 2

// wrong!!!
int error = 5; // violate one definition rule

Placement new: Dynamic Allocation

  • new & delete
  • The compiler uses 3 separate memory chunks:
    • static variable
    • automatic variable
    • dynamic storage

Namespaces

Create Named Namespace

  • The same name defined in 2 namespace will not conflict with each other
namespace Jack {
    double pail; // variable declaration
    void fetch(); // function declaration
    int pal; // variable declaration
    struct Well {...}; // struct declaration
}

namespace Jill {
    double bucket (double n) {...}
    double fetch;
    int pal;
    struct Hill {...};
}
  • Name declared inside a namespace has external linkage by default.

using Declaration and using Directives

using Jill::fetch; // declaration
using namespace Jill; // directive
  • using declaration: make a single name available
  • using directives: make all names inside the namespace available.
  • It is safer to using declaration.
namespace Jill {
    double bucket(dounle n) {...}
    double fetch;
    struct Hill {...}
}

char fetch; // global namespace

int main() {
    using namespace Jill; // import all namespace names
    Hill Thrill; // create a type Jill::Hill
    double fetch; // hide Jill::fetch

    // local fetch
    cin >> fetch;

    // global fetch
    cin >> ::fetch;

    // Jill::fetch
    cin >> Jill::fetch;
}
  • DON’T use using directives in the header file !!!
    • the order of the header files may affect behavior!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值