这是2013年写的一篇旧文,放在gegahost.net上面 http://raison.gegahost.net/?p=15

February 15, 2013

How `new’ operator works ?

Filed under: c++ — Tags: C++ internal, c++ memory layout, c++ new, POD, virtual class — Raison @ 12:38 am

(original works by Peixu Zhu)

For single inherited classes

1.  in case of single instance of a class without virtual method (inherited or not).

  • suppose the class is `theClass‘.
  • at first, it calls function `malloc‘ to allocate sizeof(theClass) memory, the size is always the same to POD structures.
  • if the `malloc‘ function fails, throw exception if `nothrow‘ is not specified.
  • if the `malloc‘ function success, call class initializer and internal initializer to set default values of members( to be zeros)
  • call the constructor on the instance as a chain, the most rooted constructor is called at first, and then the derived constructors, the latest is theClass‘s constructor.
  • set return value to be the address of `malloc‘ returned.

2.  in case of single instance of a class with virtual method (inherited or not).

  • at first, it calls functon `malloc‘ to allocate sizeof(theClass) sized memory, for single inherited class, sizeof(theClass) =  (sizeof(void*) )  +  sizeof(POD structure). the additional (sizeof(void*) ) sized memory is for purpose of storing virtual pointer table for the class and it’s parent classes.
  • if the `malloc‘ function fails, throw exception if `nothrow‘ is not specified.
  • if the `malloc‘ function success, at first, set the first (sizeof(void*)  to be the class’s virtual pointer table, and then call class initializer and  internal initializer to set default values of members( to be zeros) on subsequent memory.
  • call the constructor on the instance as a chain, the most rooted constructor is called at first, and then derived classes’ constructors, the latest is the class’s constructor.
  • set return value to be the address of `malloc‘ returned.

3.  in case of arrayed instances of a class without virtual method.

  • suppose n instances are required.
  • calculate the size of required memory:  sizeof(void*) + n * sizeof(theClass)
  • call `malloc‘ to allocate memory of the size required.
  • if `malloc‘ fails, throw exception if `nothrow‘ is not specified.
  • if `malloc‘ success, set the first sizeof(void*) the count of instances in the array (i.e. `n’).
  • for subsequent memory,  each instance is initialized and constructed as above .
  • set return value to be the address of `malloc‘ returned minus sizeof(void*), i.e., the address of first instance.

4.  in case of arrayed instances of a class with virtual method.

  • calculate the size of required memory:

sizeof(void*) + n * sizeof(theClass).
sizeof(theClass) = sizeof(void*) + sizeof(POD)

  • call `malloc‘ to allocate the size required.
  • if `malloc‘ fails, throw exception if `nothrow‘ is not specified.
  • if `malloc‘ success, set the first sizeof(void*) the count of instances in the array (i.e. `n’).
  • for subsequent memory, for each instance, set the first
    sizeof(void*) memory to be the address of virtual pointer table of the
    class, then initialize the members, and call constructor one  by one.
  • set return value to be the address of `malloc‘ returned minus sizeof(void*), i.e., the address of first instance.

5.  about the virtual pointer table.

  • the layout of virtual pointer table:

[vdes1][vdes2](vm1)(vm2)(vm3…)[typeinfo [data of typeinfo]].
square bracketing indicates optional.
each elements are pointer to functions/methods.
vdes1 and vdes2 are virtual destructor.
vm1/vm2 … are virtual methods.
typeinfo    for function `typeid‘ (std::type_info)
data of typeinfo is the data of std::type_info

  • if the class is virtual, then there is typeinfo, and data of typeinfo.
  • if the class has virtual desctructor, there’s vdes1 and vdes2. one is called by `delete‘ operator (free memory in function), and ther other one is called by `delete[]‘ operator (does not free memory in function).
  • in runtime environment, calling virtual methods are converted into
    referencing index in the virtual pointer table, the index value of each
    virtual method is determined at compiling time. In derived classes, the
    child class instance and parent class instance share the same index
    value on same virtual method (with same mangling signature). If the
    child class does not override the parent virtual method, it will set the
    indexed pointer to the parent’s method, rather than of the child,
    however, if the child class override the virtual method, it will be  the
    indexed with pointer to the child’s method.

6.  about the alignment of  address returned by `new/new[]’ operator.
As you know, `new‘ and `new[]‘ operator both call `malloc‘ function to allocate memory required, thus, the alignment of address returned by `new‘ or `new[]‘ is determined by the address returned by `malloc‘. `mallocdoes not guarantee the returned address is aligned well, thus, the `new‘ and `new[]‘ also do not guarantee the returned address is aligned well, though the size of the class is aligned.
But, there’s alignment version of `malloc‘, like posix_memalign, or valloc, etc., how about alignment version of `new‘ and `new[]‘ ?  The replacement new operator in C++11 may solve the problem.

For classes with multiple parent classes.
1. each parent class has an instance in the derived class instance, sequenced as the class definition.

2. the derived class’s own members are placed at the tail of the allocated memory.

3. sizeof(theClass) = sizeof(parentClass) * (count of parent classes) + sizeof(own)

4. for plain classes without virtual methods, sizeof(own) = sizeof(POD structure),  and for classes with virtual methods, sizeof(own) = sizeof(void*) + sizeof(POD structure).

How `new’ operator works ?的更多相关文章

  1. CLR via C# 3rd - 04 - Type Fundamentals

    1. System.Object        The runtime requires every type to ultimately be derived from the System.Obj ...

  2. Flink - Working with State

    All transformations in Flink may look like functions (in the functional processing terminology), but ...

  3. Think Python - Chapter 11 - Dictionaries

    Dictionaries A dictionary is like a list, but more general. In a list, the indices have to be intege ...

  4. MDX : Non Empty v/s NonEmpty

    MDX : Non Empty v/s NonEmpty User Rating: / 50 PoorBest Written by Jason Thomas    Friday, 07 May 20 ...

  5. NonEmpty和Non Empty的区别[转]

    One of my favourite questions in MDX is the difference between Non Empty and NonEmpty because even t ...

  6. JsonPath详解

    JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPat ...

  7. C++11 : variadic templates(可变参数模板)

      Introduction: Before the possibilities of the new C++ language standard, C++11, the use of templat ...

  8. ADF BC New Features

      Examining ADF Business Components New Features Purpose In this tutorial, you create a series of si ...

  9. Dart语言特性必备了解!

    学习Dart语言,必须将以下的概念熟记于心: 在dart语言中,一切皆为对象.所有的对象都是一个类的实例.甚至整数.函数.null也看做是对象.所有的对象都继承于Object类 尽管Dart是强类型语 ...

随机推荐

  1. codeforces 451C. Predict Outcome of the Game 解题报告

    题目链接:http://codeforces.com/problemset/problem/451/C 题目意思:有3支球队(假设编号为1.2.3),总共要打 n 场比赛,已知已经错过这n场比赛中的 ...

  2. c#-关于自动属性的思考

    参考:c#-关于自动属性的思考 我的理解:自动属性跟 公有字段 一模一样,编程习惯而已.目前是这么认为的. 自动属性:public string Name{  get;  set } 公有字段:pub ...

  3. OpenCV2.4.13+VS2012开发环境配置

    1.下载和安装OpenCV SDK 在OpenCV官网的下载页面: http://opencv.org/downloads.html   找到对应OpenCV for Windows版本下载.目前(2 ...

  4. RxJava 参考文档

    /*************************************************************** * RxJava 参考文档 * 说明: * 最近无意中发现RxJava ...

  5. I.MX6 不一定要设置BOOT_MODE进入烧录模式

    /************************************************************************* * I.MX6 不一定要设置BOOT_MODE进入 ...

  6. 【NOIP2017 DAY1T2】 时间复杂度

    [题目链接] 点击打开链接 [算法] 其实这就是一道模拟题啦! 在判error和计算时间复杂度时,我们需要用栈这种数据结构 [代码] 这题的代码还是有些难写的,写的时候一定要有条理! #include ...

  7. C - Woodcutters

    Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u Description Little ...

  8. 【WEB基础】HTML & CSS 基础入门(3)段落及文本

    写在前面:CSS选择器 网页要显示很多内容,想要为每个内容设置不同的样式,我们就得首先选中要设置样式的内容,CSS选择器就是指明该样式是针对HTML里哪一个元素的.简单的例子,网页上有几段文字,我们想 ...

  9. git操作实战指南

    1 背景 小白进入公司,进入日常多人开发,git的使用应该是新人要掌握的第一个技能.git是一个分布式数据存储库,分为远程存储和本地存储,本地存储的话,每一台计算机就相当于一个存储数据库,可以记录和存 ...

  10. POJ3468【线段树lazy操作】

    上午理论AC,打到现在快吐了... 一个那么**Lazy操作打成这样,query操作和update操作都有问题,妈蛋,发现是mid<=s+1-真是蠢到家,明明是mid+1<=s卧槽连左和右 ...