Inside the C++ Object Model - 7. On the Cusp of the Object Model

1. Template

  • Not all member functions of template class are instantiated. Only those used functions should be instantiated to same time and space.
  • Compiler may not support all operators used in member function 
Point<float> *p = new Point<float>;
//Only 
//1. float type instance of template class
//2. new operator 
//3. default constructor
//will be instantiated. 
  • scope of the template definition
  • scope of the template instantiation

Member function instantiation - 3 points need to resolve:

  1. How to find the definition of function?
  2. How to instantiate only member funtions which are invoked?
  3. How can compiler prevent instantiate member definitions in more than one .o file

2. Exception Handling

compiler build up data structure to support exception in 

  • runtime - not expand the size of program but costs some efficiency
  • compilation - increase the size of program but may be fast

How to support exception handling:

  1. check the function where throw happens
  2. see if throw is in a try block
  3. if so, compiler will check catch senteces 
  4. if it matches, catch block will take control
  5. if throw is not in a try block or no catch found, then system should 
    1. destroy all local active objects
    2. unwind current function from stack
    3. go to next function in the stack and repeat 2-5

3. Runtime Type Identification, RTTI

Overhead of doing cast in C++:

  • additional space to store type_info object in vtbl
  • additional time cost to decide runtime type

Dynamic cast is safe, return 0 if cast fails. The cost of dynamic cast is that compiler will create a type descriptor and it can be accessed through vptr.

((type_info*)(pt->vptr[0]))->_type_descriptor;

Typeid operator

class TestClass{};

TestClass temp;
typeid(temp).name();          // "class TestClass"
typeid(temp).raw_name();      // ".?AVTestClass" - decided by compiler

Pointer and reference:

// nullptr, no object is pointed to. 
Point<float> *ptr = 0;
// it will instantiate a point instance
// which will be converted to
// Point<float> temp(float(0));
// const Point<float> &ref = temp;
const Point<float> &ref = 0;

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值