对象模型
1、vptr和vtbl(虚函数与虚表)
调用虚函数vfun,通过虚指针vptr找到虚表vtbl,通过虚表指向虚函数位置实现调用。

内存模型

以PPT内绘制图形为例

多态
2、this(this指针)
虚函数的应用场景,template method。

Template Method实现过程

this指代子类对象

动态绑定/多态
3、Dynamic binding(动态绑定)

静态绑定

动态绑定
pa指针,new的是B类型的对象,向上转型为A,调用虚函数vfunc1()-------》动态绑定

call的结果不同
new &delete
// Global里关于new 和delete的定义
inline void* operator new(size_t size ) {
size_t* p=(size_t*)malloc(size);
cout<<"Global::operator new().\tsize="<<size<<"\treturn:"<<p<<endl;
return p;
}
inline void operator delete(void* pdead,size_t size) {
cout<<"Global::operator delete().\tpdead="<<pdead<<"\tsize="<<size<<endl;
free(pdead);
}
inline void* operator new[](size_t size ) {
size_t* p=(size_t*)malloc(size);
cout<<"Global::operator new[]().\tsize="<<size<<"\treturn:"<<p<<endl;
return p;
}
inline void operator delete[](void* pdead,size_t size) {
cout<<"Global::operator delete[]().\tpdead="<<pdead<<"\tsize="<<size<<endl;
free(pdead);
}
//以上内容有代码,请复制后查看= =
//全局重载影响重大,使用需谨慎

全局重载

new delete 重载解析

new【 】 delete【 】重载解析

接口设计范例

结果显示

强制全局new 与delete 调用结果显示

重载new() delete()

抛出异常示例

抛出异常结果测试。显示有可能调用不到此函数
调用不到此函数的原因:1、异常无法处理,回收内存失败。2、可以通过new 与delete 全局回收,不需要写此函数。(个人猜测)

标准库中basic_string案例
const 补充

成员函数const 位置,表示内容不做修改。
只有成员函数const 才能放在这个位置,表示内容不做修改。一般的全局函数const不能放在这里。

const说明
常量(const)对象只能调用常量(cosnt)函数,调用非常量函数会出错。
非常量对象可调用const 函数,也可调用非常量函数。
设计时,能加const的都加const。
const 属于签名的一部分。

COW模式

常量和非常量同时存在,常对常,非常对非常
网友评论