Initialization of shared_ptr from unique_ptr

前端 未结 1 1063
慢半拍i
慢半拍i 2021-01-12 02:28

[Followup to this question]

I\'ve been dealing a little bit with smart pointers to c-style arrays recently. I ultimately wound up doing the recommended thing and usi

相关标签:
1条回答
  • 2021-01-12 03:18

    Yes, your example is valid for the very reasons you've stated. unique_ptr::pointer is int *, and you're trying to pass ownership of that to a shared_ptr<int>, so the converting constructor you've listed will participate in overload resolution, and will make a copy of the deleter (std::default_delete<int[]>) because it's not a reference type.

    So the following is valid, and will call delete[] when the shared_ptr reference count goes to zero

    std::shared_ptr<T> mySharedArray = std::make_unique<T[]>(16);
    

    Another way to write this, other than the lambda you've shown, is

    std::shared_ptr<T> mySharedArray(new T[16], std::default_delete<int[]>());
    

    which will result in mySharedArray acquiring the same deleter as the previous line.

    0 讨论(0)
提交回复
热议问题