what's the point of std::unique_ptr::get

前端 未结 6 1967
半阙折子戏
半阙折子戏 2020-12-04 21:45

Doesn\'t std::unique_ptr::get defeat the purpose of having a unique_ptr in the first place? I would have expected this function to change its state so it holds

6条回答
  •  生来不讨喜
    2020-12-04 22:10

    When your hands are tied and you do need to pass a pointer to something, p.get() reads better than &*p.

    There is a function that changes the state so the unique_ptr doesn't hold a pointer anymore, and that one is named release. This is mostly useful to transfer ownership to other smart pointers that don't provide direct construction from a unique_ptr. Any other use risks leaking the resource.

提交回复
热议问题