What happens when using make_shared

后端 未结 3 625
[愿得一人]
[愿得一人] 2020-12-14 01:20

I\'m interested if these two lines of code are the same:

shared_ptr sp(new int(1)); // double allocation?
shared_ptr sp(make_shared<         


        
3条回答
  •  情书的邮戳
    2020-12-14 02:04

    Explanation from cppreference std::shared_ptr in Implementation notes section

    In a typical implementation, std::shared_ptr holds only two pointers:

    1. a pointer to the managed object
    2. a pointer to control block

    When shared_ptr is created by calling std::make_shared or std::allocate_shared, the memory for both the control block and the managed object is created with a single allocation. The managed object is constructed in-place in a data member of the control block. When shared_ptr is created via one of the shared_ptr constructors, the managed object and the control block must be allocated separately. In this case, the control block stores a pointer to the managed object.

提交回复
热议问题