Lecture 3

notion image
  • stack
    • local vars
  • heap
    • dynamically allocated vars
  • code/data
    • global vars
    • static global vars
    • static local vars

Global vars


  • vars defined outside any functions
  • can be shared btw .cpp files
  • extern
 

extern

extern is a declaration says there will be such a variable somewhere in the whole program
“such a” means the type/name of the variable
global variable is a definition, the storage place for that variable
定义的地方是真正创建 vars 的地方,会在这里分配空间给 vars

static

static global variable inhibits the access outside its .cpp file, so as the static function
static local vars
keep its state in between multiple visits to its function, and is initialized at its first access
两大特性:
  • restricted access scope
  • persistent storage

Pointers to objects


operators:
  • get address
    • ps = &s;
  • get the object
    • (*ps).length()
  • call the function
    • ps->length()
两种方式:
  • string s;
    • 创建后自动初始化
  • string *ps;
    • 指针指向哪还不知道

Reference


char& r = c
相当于 rc 的一个别名,实际是一个东西;任意一方有改动另一方也会一起改动
两种定义形式
  • type& refname = name;
    • for ordinary definition
    • an initial value is required
  • type& name;
    • in parameter lists or member variables
    • initialized by caller or constructor

Rules of references

  • 不可以被重绑定
    • e.g.
  • the target of a non-const reference must be an lvalue
  • no references to references
  • no pointer to reference, but reference to pointer is ok
  • no arrays of reference
notion image

Dynamic memory allocation


  • new
  • delete
new 类似mallocdelete 类似free
主要的不同在于:
new 会自动调用构造函数,delete 会自动调用析构函数。malloc free 只分配释放内存。(没太搞懂析构函数)
notion image

Constant


const : declares a variable to have a constant value
默认是 internal linkage,即只能在该 .cpp 内访问
C++ 编译器通常会 在符号表(Symbol Table)中存储常量值,而不是实际分配内存
如果想要跨文件共享 const 常量,需要显式使用 extern 强制分配存储空间
e.g.
 
Loading...
文章列表

没有找到文章