我可以在依赖注入中使用std::unique_ptr吗?

c++ Can I use std::unique_ptr with dependency injection?

本文关键字:unique ptr std 依赖 注入 我可以      更新时间:2023-10-16

我一直在使用原始指针进行依赖注入,我决定将代码转换为使用shared_ptr。这是有效的,但我想知道我是否可以使用unique_ptr代替?在下面的例子中,MyClass将管理信用卡服务的生命周期。

class PaymentProcessor
{
    PaymentProcessor(?? creditCardService):
      :creditCardService_(creditCardService)
      {
      }
private:
   CreditCardService *creditCardService_;     
}
class MyClass
{ 
public:
   void DoIt()
   {
     creditCardService_.reset(new VisaCardService());
     PaymentProcessor pp(creditCardService_);
     pp.ProcessPayment();
   }
private:   
   std::unique_ptr<CreditCardService> creditCardService_;
}

你可以传递一个unique_ptr到另一个类,另一个类只是"使用"指针(不拥有它??)?如果是这样,这是一个好主意吗? PaymentProcessor的构造函数中参数的类型应该是什么?

在上面所示的示例中,我可以在堆栈上创建一个VisaCardService变量,并让PaymentProcessor构造函数将其作为引用参数。这似乎是推荐的c++实践。然而,在creditCardService_的具体类型直到运行时才知道的情况下(例如,用户选择在运行时使用特定的信用卡服务),使用std::unique_ptr与引用是最好的解决方案吗?

你能传递一个unique_ptr给另一个类吗只是"使用"指针(不拥有它??)?

在这种情况下,将指针改为reference:
class PaymentProcessor
{
public:
    PaymentProcessor(CreditCardService & creditCardService_):
      :creditCardService_(creditCardService_)
      {
      }
private:
   CreditCardService &creditCardService_;     
};
   void DoIt()
   {
     creditCardService_.reset(new VisaCardService());
     PaymentProcessor pp(*creditCardService_);
     pp.ProcessPayment();
   }

如果你仍然想使用指针,那么你需要使用get方法:

class PaymentProcessor
{
public:
    PaymentProcessor(CreditCardService * creditCardService_):
      :creditCardService_(creditCardService_)
      {
      }
private:
   CreditCardService *creditCardService_;     
};
   void DoIt()
   {
     creditCardService_.reset(new VisaCardService());
     PaymentProcessor pp(creditCardService_.get());
     pp.ProcessPayment();
   }