How to approach copying objects with smart pointers as class attributes?

后端 未结 5 616
小鲜肉
小鲜肉 2021-01-02 16:15

From the boost library documentation I read this:

Conceptually, smart pointers are seen as owning the object pointed to, and thus responsible for de

5条回答
  •  攒了一身酷
    2021-01-02 16:41

    You have two solutions ( actually you have many more, but these make most sense to me :) ):

    First, you can use std::unique_ptr. This is a good solution because it forces you to have one instance per pointer. (using std::shared_ptr instead would work as well, but if you do not add the code explicitely, copy and assignment for shared_ptr will "share" - especially what you want to avoid).

    If you use std::unique_ptr, your copy constructor and assignment operator should explicitly deep-copy (using either a virtual clone method in the pointee's interface, or new operator in the call to the unique_ptr constructor).

    Second, you can roll your own. There's nothing complicated about it, and we're talking about a small (10-20 lines or so) utility class.

    Personally, if I had to use this smart pointer class in one place, I would use std::unique_ptr. Otherwise (multiple pointers, same behavior) I would roll my own, simply so I wouldn't have to repeat the deep copy for many instances (to keep with the DRY principle).

提交回复
热议问题