I don't understand why I declare an empty internal structure and pass it in the constructor

Viewed 111

When I read the source code of Hypodermic, I found an empty structure declared in the constructor of its container. I don't understand why it did this?

class Container : public std::enable_shared_from_this< Container >
{
   private:
     struct PrivateKey {};
   
   public:
     Container(const PrivateKey&,
                  const std::shared_ptr< IRegistrationScope >& registrationScope,
                  const std::shared_ptr< IRuntimeRegistrationBuilder >& runtimeRegistrationBuilder)
            : m_registrationScope(registrationScope)
            , m_runtimeRegistrationBuilder(runtimeRegistrationBuilder)
     {
     }

     static std::shared_ptr<Container> create(const std::shared_ptr<IRegistrationScope>& registrationScope,
                                                   const std::shared_ptr<IRuntimeRegistrationBuilder>& runtimeRegistrationBuilder)
     {
        return std::make_shared<Container>(PrivateKey(), registrationScope, runtimeRegistrationBuilder);
     }

     // other code...
};

PrivateKey is defined in the above code, I don’t understand what problem it solves. It doesn't seem to do anything.

1 Answers

As @Eljay stated in a comment, the constructor has to be accessible when using std::make_shared.

The idea behind this factory method is to make sure no component will get an instance of Container that is not a std::shared_ptr thus enforcing the legitimacy of shared_from_this() inside Container methods.

If you need further explanation, feel free to reach me through GitHub.

Related