How do I call ::std::make_shared on a class with only protected or private constructors?

前端 未结 16 2638
遥遥无期
遥遥无期 2020-11-22 09:07

I have this code that doesn\'t work, but I think the intent is clear:

testmakeshared.cpp

#include 

class A {
 public:
   stat         


        
16条回答
  •  有刺的猬
    2020-11-22 09:46

    There's a more hairy and interesting problem that happens when you have two strictly related classes A and B that work together.

    Say A is the "master class" and B its "slave". If you want to restrict instantiation of B only to A, you'd make B's constructor private, and friend B to A like this

    class B
    {
    public:
        // B your methods...
    
    private:
        B();
        friend class A;
    };
    

    Unfortunately calling std::make_shared() from a method of A will make the compiler complain about B::B() being private.

    My solution to this is to create a public Pass dummy class (just like nullptr_t) inside B that has private constructor and is friend with A and make B's constructor public and add Pass to its arguments, like this.

    class B
    {
    public:
      class Pass
      {
        Pass() {}
        friend class A;
      };
    
      B(Pass, int someArgument)
      {
      }
    };
    
    class A
    {
    public:
      A()
      {
        // This is valid
        auto ptr = std::make_shared(B::Pass(), 42);
      }
    };
    
    class C
    {
    public:
      C()
      {
        // This is not
        auto ptr = std::make_shared(B::Pass(), 42);
      }
    };
    

提交回复
热议问题