Dependency injection w/ smart pointers in C++ -
i'm trying implement dependency injection pattern in c++ project, performing injection manually (no framework). i'm using factory function manually create dependencies , pass them classes use them. problem when root of dependency graph (itself class instance managed smart pointer) goes out of scope, dependencies (smart pointers referenced within class) don't destroyed (valgrind shows lost blocks of memory).
i'm seeing basic example this, class depends on class b:
class b{ public: b() {} ~b() {} }; class a{ std::unique_ptr<b> b_; public: a(std::unique_ptr<b> b) : b_(std::move(b)) { } ~a(){} }; namespace a_factory { std::unique_ptr<a> getinstance(){ return std::make_unique<a>(std::make_unique<b>()); } } int main(void){ auto = a_factory::getinstance(); //do stuff } //a goes out of scope , gets deleted?
so in example use a_factory::getinstance
a, whatever using doesn't know how created, nor know how dependency created. , understanding smart pointers they'd automatically delete when going out of scope, which chain down dependency graph once root goes out of scope. if had implement code destroy dependencies i'm not getting benefit smart pointer.
so can't tell if i'm not setting things right smart pointers, or perhaps valgrind isn't telling me think means. understanding valgrind it's pointing out issues within scope of my code, if standard library deleting dependencies valgrind may not reflect that. when run valgrind against simple program using smart pointer wrapped around trivial class (no dependencies) doesn't show lost memory.
i'll note examples i've seen here on stackoverflow have no worked me, not calling std::move
in a's initialization list. , i'd avoid raw pointers being passed around.
i'm using g++ 4.8.5 doesn't include make_unique i've added herb sutter's suggested make_unique implementation , run test under valgrind shows no leaking.
#include <iostream> #include <cstdlib> #include <memory> using namespace std; template<typename t, typename ...args> std::unique_ptr<t> make_unique(args&& ...args) { return std::unique_ptr<t>(new t ( std::forward<args>(args)...)); } class b{ public: b() {} ~b() {} }; class a{ std::unique_ptr<b> b_; public: a(std::unique_ptr<b> b) : b_(std::move(b)) { } ~a(){} }; namespace a_factory { std::unique_ptr<a> getinstance(){ return make_unique<a>(make_unique<b>()); } } int main(void){ auto = a_factory::getinstance(); }
perhaps problem stems make_unique implementation in whatever compiler you're using?
Comments
Post a Comment