What happens when using make_shared

后端 未结 3 419
[愿得一人]
[愿得一人] 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:16

    There is also a potential subtle bug: in sp(new int) you fist allocate an int (whose pointer is given to sp), than sp itself has to allocate a control block (will contain the counters and the deleter).

    Now, if doing this last allocation sp fails (low memory) you are left with a heap allocated int whose pointer is not held by anyone, and thus impossible to delete. (memory leak).

提交回复
热议问题