Dependency injection with unique_ptr to mock
After all, I ended up using this approach everywhere:
struct FooTest : public Test {
FooTest() : barMock{new BarMock} {
auto ptr = unique_ptr<BarMock>(barMock);
out.reset(new Foo(std::move(ptr)));
}
BarMock* barMock;
unique_ptr<Foo> out;
};
and it works fine with gtest/gmock
.
Memory leak warning when using dependency injection using a unique_ptr containing a mocked interface
std::unique_ptr<Base> base = std::move(mock);
is where the memory leak happens: *base
will be destroyed as a Base
, not a Mock
, when base
is destroyed.
The best fix is to add a virtual destructor (virtual ~Base() = default;
), which you should have for a struct that has any other virtual members.
c++ Can I use std::unique_ptr with dependency injection?
Can you pass a unique_ptr to another class where the other class is
just "using" the pointer (without owning it??)?
In that case, change the pointer to reference :
class PaymentProcessor
{
public:
PaymentProcessor(CreditCardService & creditCardService_):
:creditCardService_(creditCardService_)
{
}
private:
CreditCardService &creditCardService_;
};
void DoIt()
{
creditCardService_.reset(new VisaCardService());
PaymentProcessor pp(*creditCardService_);
pp.ProcessPayment();
}
If you still want to use a pointer, then you need to use get
method :
class PaymentProcessor
{
public:
PaymentProcessor(CreditCardService * creditCardService_):
:creditCardService_(creditCardService_)
{
}
private:
CreditCardService *creditCardService_;
};
void DoIt()
{
creditCardService_.reset(new VisaCardService());
PaymentProcessor pp(creditCardService_.get());
pp.ProcessPayment();
}
Related Topics
May Std::Vector Make Use of Small Buffer Optimization
Does the Gotw #101 "Solution" Actually Solve Anything
Using Assignment as a Condition Expression
Why Floating Point Value Such as 3.14 Are Considered as Double by Default in Msvc
Should I Return Exit_Success or 0 from Main()
What Do C and Assembler Actually Compile To
Tmp: How to Generalize a Cartesian Product of Vectors
Is the Backslash Acceptable in C and C++ #Include Directives
C++: Safe to Use Longjmp and Setjmp
Unsequenced Value Computations (A.K.A Sequence Points)
How to Add 2 Arbitrarily Sized Integers in C++
Getdibits and Loop Through Pixels Using X, Y
How to Identify Platform/Compiler from Preprocessor MACros