我可以在依赖注入中使用std::unique_ptr吗?
c++ Can I use std::unique_ptr with dependency injection?
我一直在使用原始指针进行依赖注入,我决定将代码转换为使用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
与引用是最好的解决方案吗? 在这种情况下,将指针改为reference:你能传递一个unique_ptr给另一个类吗只是"使用"指针(不拥有它??)?
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();
}
相关文章:
- 为什么 std::unique 不调用 std::sort?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 生成"unique"矩阵
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 我对 std::unique(算法)C++有问题
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- std::shared_ptr::unique(),复制和线程安全
- 如何在C++03中用自定义谓词调用std::unique
- C++中的指针否定 (!ptr == NULL)
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误