C++ 面向对象高级编程 (下) week 2 (Boolan)

对象模型(Object Model): 关于vptr/vtbl和Dynamic Binding

  • 对象模型图(关于vptr和vtbl):


    vptr1.jpeg

    评论: 实现动态绑定, 要满足三个条件: 1. 通过指针来调用; 2. 指针可向上转型;3. 通过虚函数调用.

  • virtual function的应用场景1:


    vptr2.jpeg
  • virtual function的应用场景2:


    vptr3.jpeg

关于vptr/vtbl 和 Dynamic Binding(摘自Thinking in C++):

How can late binding (注: 即dynamic binding) happen? All the work goes on behind the scenes by the compiler, which installs the necessary late-binding mechanism when you ask it to (you ask by creating virtual functions).
The keyword virtual tells the compiler it should not perform early binding. Instead, it should automatically install all the mechanisms necessary to perform late binding. This means that if you call a virtual function for the Derived object through an address for the Base class, you’ll get the proper function.
To accomplish this, the typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object. When you make a virtual function call through a base-class pointer (that is, when you make a polymorphic call), the compiler quietly inserts code to fetch the VPTR and look up the function address in the VTABLE, thus calling the correct function and causing late binding to take place.
All of this – setting up the VTABLE for each class, initializing the VPTR, inserting the code for the virtual function call – happens automatically, so you don’t have to worry about it. With virtual functions, the proper function gets called for an object, even if the compiler cannot know the specific type of the object.

谈谈const

const.jpeg

一些补充(摘自Effective C++):

Use const whenever possible. Things to Remember:

  • Declaring something const helps compilers detect usage errors. const can be applied to objects at any scope, to function parameters and return types, and to member functions as a whole.
  • Compilers enforce bitwise constness, but you should program using logical constness.
  • When const and non-const member functions have essentially identical implementations, code duplication can be avoided by having the non-const version call the const version.

重载new和delete

重载::operator new, ::operator delete, ::operator new[] 和 ::operator delete[]:

void* myAlloc(size_t size) { return malloc(size); }
void myFree(void* ptr) { return free(ptr); }

// These functions cannot be declared within any namespace
inline void* operator new(size_t size) {
  cout << "jjhou global new() \n";
  return myAlloc(size);
}

inline void* operator new[](size_t size) {
  cout << "jjhou global new[]() \n";
  return myAlloc(size);
}

inline void operator delete(void* ptr) {
  cout << "jjhou global delete() \n";
  return myFree(ptr);
}

inline void operator delete[](void* ptr) {
  cout << "jjhou global delete[]() \n";
  return myFree(ptr);
}

重载member operator new/delete, new[]/delete[]:

class Foo {
 public:
  static void* operator new(size_t size)  {
    Foo* p = (Foo*)malloc(size);
    cout << "Foo::operator new()" << endl;
    return p;
  }
  static void operator delete(void* pdead, size_t size) { 
  // size is optional
    cout << "Foo::operator delete()" << endl;
    free(pdead);
  }
  static void* operator new[](size_t size) {
    Foo* p = (Foo*)malloc(size);
    cout << "Foo::operator new[]()" << endl;
    return p;
  }
  static void operator delete[](void* pdead, size_t size) { 
  // size is optional
    cout << "Foo::operator delete[]()" << endl;
    free(pdead);
  }

  // ... 
};

Foo* p1 = new Foo;
Foo* p2 = new Foo[N];
...
delete p1;
delete [] p2;

编译器如何选择new/delete操作?(摘自C++ Primer)

Applications can define operator new and operator delete functions in the global scope and/or as member functions. When the compiler sees a new or delete expression, it looks for the corresponding operator function to call. If the object being allocated (deallocated) has class type, the compiler first looks in the scope of the class, including any base classes. If the class has a member operator new or operator delete, that function is used by the new or delete expression. Otherwise, the compiler looks for a matching function in the global scope. If the compiler finds a user-defined version, it uses that function to execute the new or delete expression. Otherwise, the standard library version is used.

placement new

我们可以重载class member operator new(), 写出很多版本, 前提是没一个版本的声明都必须有独特的参数列, 其中第一参数必须是size_t, 其余参数以new所制定的placement argument为初值. 出现于new(...)小括号内的便是所谓的placement argument.

Foo* pf = new (300, 'c') Foo;

我们也可以重载class member operator delete(), 写出很多版本. 但它们绝不会被delete调用. 只有当new所调用的ctor抛出exception, 才会调用这些重载版的operator delete(). 它只可能这样被调用, 主要用来归还未能完全创建成功的object所占用的memory.

如何写placement new:


pnew.jpeg

如何写placement delete:


pdel.jpeg

评论: 在视频课程中, 老师举了一个basic_string中使用placement new的例子, 示例中placement new被用来无声无息的扩充申请的memory的大小. 而在C++的早期版本中, placement new更多的被用来实现allocation和initialization的分离(摘自C++ Primer):

In earlier versions of the language—before the allocator class was part of the library—applications that wanted to separate allocation from initialization did so by calling operator new and operator delete. These functions behave analogously to the allocate and deallocate members of allocator. Like those members, operator new and operator delete functions allocate and deallocate memory but do not construct or destroy objects. Differently from an allocator, there is no construct function we can call to construct objects in memory allocated by operator new. Instead, we use the placement new form of new to construct an object. This form of new provides extra information to the allocation function.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容