Lecture 5

Ctor and Dtor


Guaranteed initialization

With a constructor (Ctor)
  • the compiler ensure its call when an object is created
  • use the name as the class
e.g.
  • The constructor can have arguments
    • specify how an object is created
    • give it initialization values
e.g.

Guaranteed cleanup

With a destructor (Dtor)
  • the complier ensures its call when an object is about to end its life-cycle
  • the name of the class with a leading tilde ( ~ )
  • no arguments at all
e.g.

RAII

Resource acquisition is initialization
把一个资源的周期和对象的周期绑定在一起
  • acquire resources in Ctor
  • release resources in Dtor

The default constructor

A default constructor is one that can be called with no arguments.
e.g.
合法初始化:
  • Y y1[] = {Y(1), Y(2), Y(3)};
非法初始化(Ctor 表明需要变量,但初始化时没有给出):
  • Y y2[2] = {Y(2)};
  • Y y3[7];
  • Y y4;
没有定义任何构造函数时,编译器会自动定义一个auto default constructor
 

Initializer list


  • Assignment in the body is not initialization
  • The order of initialization is the order of fields declaration, not the one in the initializer list
e.g.
但如果我们不使用初始化列表,而直接赋值:
会报错:
notion image
此时 y = 10; 并非初始化而是赋值,会先调用 Y 的默认构造函数,再执行赋值操作,但 Y 中不含默认构造函数,所以报错
若我们在结构体定义中加一个默认构造函数:
程序就可以正常执行
这里的赋值 y = 10; 是在没有 explicit 修饰构造函数时,单参数构造函数可以隐式类型转换。若把构造函数改为:
赋值就必须显示调用 y = Y(10);
notion image

Local variables vs. Field


e.g
Lifetime:
  • amountToRefund is with the function call
  • balance is with the object, i.e., object state

Fields

class 或 struct 中的成员变量,也称字段/ data member
结构体中字段的默认访问修饰符是 public ,类中是 private

this : the hidden parameter


this 是所有 member function 中的隐藏变量,如 void Print::print() 可以被看作是 void Print::print(Point *this)

Const member function


当 object 有 const 修饰时,会调用 const member function
e.g.
void foo() const 相当于 void foo(const X * this)
如果字段用 const 修饰,在构造函数中只能用初始化列表做初始化,而不允许在构造函数中赋值

Static


此时, data 是字段,每创建一个 object 都会给对应的 data 开辟内存空间;用 static 修饰 data ,在结构体内只声明了会有个一个名为 “data” 的变量,但不是定义,需要在外部定义:
此时 object abdata 字段值均为 20,因为都来自全局变量。此时的 data 可以直接在外部访问:A::data
member function 也可以用 static 修饰,如
此时, foo 函数可以直接在外部调用:A::foo(30) ,但此时 member function 不与对象绑定,也不会默认传递 this 参数

Overhead for a function call


The extra processing time required:
  • Push parameters
  • Push return address
  • Prepare return value
  • Pop all pushed
 
Loading...