美文网首页
C++ 面向对象高级编程 (下) week 2 (Boolan)

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

作者: YPAN | 来源:发表于2017-11-19 21:59 被阅读0次

    对象模型(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.

    相关文章

      网友评论

          本文标题:C++ 面向对象高级编程 (下) week 2 (Boolan)

          本文链接:https://www.haomeiwen.com/subject/aacuvxtx.html