How to make boost::make_shared a friend of my class

后端 未结 6 1335
借酒劲吻你
借酒劲吻你 2021-02-03 12:28

I have written a class with protected constructor, so that new instances can only be produced with a static create() function which returns shared_ptr\'s to my class. To provide

6条回答
  •  悲哀的现实
    2021-02-03 13:27

    I ended up using the below simple solution to enforce shared ownership. No friendship required.

    class probe {
        probe() = default;
        probe(...) { ... }
    
        // Part I of III, private
        struct creation_token {};
        probe(probe const&) = delete;
        probe& operator=(probe const&) = delete;
    
    public:
        // Part II of III, public
        template 
        probe(creation_token&&, Args&&... args):
            probe(std::forward(args)...) {}
    
        // Part III of III, public
        template 
        static auto create(Args&&... args) {
            return make_shared(creation_token(),
                std::forward(args)...);
        }
    };
    

提交回复
热议问题