我不明白为什么我声明一个空的内部结构并在构造函数中传递它

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

当我阅读Hypodermic的源代码时,我发现在其容器的构造函数中声明了一个空结构。我不明白为什么要这样做?

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,我不明白它解决了什么问题。好像没什么作用。

正如@Eljay 在评论中所述,使用 std::make_shared.

时必须可以访问构造函数

这个工厂方法背后的想法是确保没有组件会得到一个不是 std::shared_ptrContainer 的实例,从而加强 shared_from_this() [=21= 的合法性]内部 Container 方法。

如果您需要进一步的解释,请随时通过 GitHub 与我联系。