Should I use shared_ptr or unique_ptr

前端 未结 4 1078
半阙折子戏
半阙折子戏 2020-11-30 03:29

I\'ve been making some objects using the pimpl idiom, but I\'m not sure whether to use std::shared_ptr or std::unique_ptr.

I understand that std::unique_ptr

4条回答
  •  猫巷女王i
    2020-11-30 04:22

    If you use shared_ptr, it's not really the classical pimpl idiom (unless you take additional steps). But the real question is why you want to use a smart pointer to begin with; it's very clear where the delete should occur, and there's no issue of exception safety or other to be concerned with. At most, a smart pointer will save you a line or two of code. And the only one which has the correct semantics is boost::scoped_ptr, and I don't think it works in this case. (IIRC, it requires a complete type in order to be instantiated, but I could be wrong.)

    An important aspect of the pimpl idiom is that its use should be transparent to the client; the class should behave exactly as if it were implemented classically. This means either inhibiting copy and assignment or implementing deep copy, unless the class is immutable (no non-const member functions). None of the usual smart pointers implement deep copy; you could implement one, of course, but it would probably still require a complete type whenever the copy occurs, which means that you'd still have to provide a user defined copy constructor and assignment operator (since they can't be inline). Given this, it's probably not worth the bother using the smart pointer.

    An exception is if the objects are immutable. In this case, it doesn't matter whether the copy is deep or not, and shared_ptr handles the situation completely.

提交回复
热议问题