生活随笔
收集整理的這篇文章主要介紹了
C++程序运行时内存布局之--无继承情况下的虚函数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
虛函數(shù)是C++實現(xiàn)多態(tài)的關鍵,沒有虛函數(shù),C++只能是OB,不能完成OO。
本文介紹的是沒有繼承情況下,帶有虛函數(shù)的類在內(nèi)存中布局,以及其實例(對象)內(nèi)存布局。
?
1.源碼
view plain
#include?<iostream>??#include?<stdio.h>????using?namespace?std;????class?CVirtual??{??public:??????int?x;??public:??????virtual?void?VF()??????{??????????cout<<this->x<<endl;??????????cout<<"hello"<<endl;??????}??public:??????CVirtual(int?x)??????{??????????this->x?=?x;??????}??};????typedef?void?(CVirtual::*Fun)();??union??{??????Fun?f;??????unsigned?int?addr;??}ut;????int?main(int?argc,?char**?argv)??{????????????cout<<"對象大小為???????????????????????:"<<sizeof(CVirtual)<<endl;????????CVirtual?*p?=?new?CVirtual(999);??????CVirtual?*p1?=?new?CVirtual(888);??????????????cout<<"新建對象的地址???????????????????:"<<p<<endl;??????????????cout<<"對象中第一個成員變量的地址???????:"<<&p->x<<endl;??????????????ut.f?=?&(CVirtual::VF);??????cout<<"類中第一個虛函數(shù)的地址???????????:"<<std::hex<<std::showbase<<ut.addr<<endl;??????????????unsigned?int?vptr?=?*((unsigned?int*)p);??????cout<<"對象1中虛表指針(即虛表地址)為????:"<<std::hex<<std::showbase<<vptr<<endl;??????????????unsigned?slot0?=?*((unsigned?int*)vptr);??????cout<<"虛表中第一項的值(第一個虛函數(shù)地址):"<<std::hex<<std::showbase<<slot0<<endl;????????????????unsigned?int?vptr1?=?*((unsigned?int*)p1);??????cout<<"對象2中虛表指針(即虛表地址)為????:"<<std::hex<<std::showbase<<vptr1<<endl;??????????????unsigned?slot01?=?*((unsigned?int*)vptr1);??????cout<<"虛表中第一項的值(第一個虛函數(shù)地址):"<<std::hex<<std::showbase<<slot01<<endl;????????????????typedef?void?(__thiscall?*MyFun)(void*?pThis);??????????????MyFun?f?=?(MyFun)slot0;??????f(p);??????????????MyFun?f1?=?(MyFun)ut.addr;??????f1(p);????????delete?p;??????delete?p1;???????cin>>argc;??}?? ?
2.結果
?
3.內(nèi)存布局圖
4.結論
- 虛函數(shù)表在編譯期間已經(jīng)確定,建立在data區(qū),運行期只是把由構造函數(shù)把對象的vptr值設定為這個地址,同一個類的所有實例共享同一個虛函數(shù)表;
- 虛函數(shù)表中的每一個項目不一定是虛函數(shù)的地址,很可能是一個代理函數(shù),然后由代理函數(shù)再調(diào)用虛函數(shù);
轉載于:https://my.oschina.net/kaixindewo/blog/28519
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎
總結
以上是生活随笔為你收集整理的C++程序运行时内存布局之--无继承情况下的虚函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。