I find myself often in the situation where I want to mock a non-copyable object, for example a DbHandleDbHandle handle.
I was going back and forth looking at different design choices, and I settled on the following design:
In my production code, there is no need for a client of the RepositoryRepository to konwknow the DbHandleDbHandle object, but for the unit tests, this DbHandleDbHandle object is exctlyexactly the one I want to mock.
I settled for unique_ptrunique_ptr because they make clear that the RespositoryRespository owns the DbHandleDbHandle, even if it is created outside.
#include <memory> class Repository { public: Repository() : d_dbHandel(std::unique_ptr<DbHandel>(new DbHandle("default"))) { d_dbHandel->open("myDB"); } Repository(std::unique_ptr<DbHandle> DbHandle) : d_dbHandel(std::move(DbHandle) { } inline DbHandle& getDbHandel() { return *d_dbHandel; } private: std::unique_ptr<DbHandel> d_dbHandel; }; What are some of the flaws of this approach?