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

后端 未结 6 1320
借酒劲吻你
借酒劲吻你 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

    Just a summary of how a complete version may look like:

    #include 
    #include 
    
    class Foo {
      explicit Foo(int x) {
        std::cout << "Foo::Foo(" << x << ")\n";
      }
    public:
      friend boost::shared_ptr boost::make_shared(const int& x);
    
      static boost::shared_ptr create(int x) {
        return boost::make_shared(x);
      }
    
      ~Foo() {
        std::cout << "Foo::~Foo()\n";
      }
    };
    
    int main(int argc, const char *argv[]) {
      Foo::create(42);
    }
    

提交回复
热议问题