Cannot move std::unique_ptr with NULL deleter to std::shared_ptr?

前端 未结 2 966
刺人心
刺人心 2021-01-22 12:36

I want to move a NULL std::unique_ptr to a std::shared_ptr, like so:

std::unique_ptr test = nullptr;
std::shared_ptr          


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-22 13:26

    The unique_ptr constructor you are trying to use, which default-constructs the deleter, is ill-formed (before C++17) or disabled by SFINAE (as of C++17) if the deleter type is a pointer, in order to stop you from accidentally creating a unique_ptr whose deleter is itself a null pointer. If you really want to create such a unique_ptr, you can do so by explicitly passing a null deleter:

    std::unique_ptr test(nullptr, nullptr);
    

    This unique_ptr object is not very useful, because it can't delete anything.

    By using a null std::function deleter, you've told the compiler "yes, I really want to shoot myself in the foot". Of course, when the last std::shared_ptr is destroyed, the null std::function is invoked, and undefined behaviour occurs. What else did you expect?

提交回复
热议问题