Why is the size of make_shared two pointers?

后端 未结 4 1043
傲寒
傲寒 2021-02-05 03:23

As illustrated in the code here, the size of the object returned from make_shared is two pointers.

However, why doesn\'t make_shared work like the following

4条回答
  •  萌比男神i
    2021-02-05 04:14

    Others have already said that shared_ptr needs two pointers because it has to point to the reference count memory block and the Pointed to Types memory Block.

    I guess what you are asking is this:

    When using make_shared both memory blocks are merged into one, and because the blocks sizes and alignment are known and fixed at compile time one pointer could be calculated from the other (because they have a fixed offset). So why doesn't the standard or boost create a second type like small_shared_ptr which does only contain one pointer. Is that about right?

    Well the answer is that if you think it through it quickly becomes a large hassle for very little gain. How do you make the pointers compatible? One direction, i.e. assigning a small_shared_ptr to a shared_ptr would be easy, the other way round extremely hard. Even if you solve this problem efficiently, the small efficiency you gain will probably be lost by the to-and-from conversions that will inevitably sprinkle up in any serious program. And the additional pointer type also makes the code that uses it harder to understand.

提交回复
热议问题