'Dependency Injection with Shared pointer instead of Singleton in C++
I am trying to implement 2 or more classes that are going to use the same shared memory through a wrapper class as a dependency.
My doubt: Can shared pointer substitute Singleton ?
Note: I am trying to avoid Singleton for unit-test purpose.
Below is sample code for reference. Is this implementation fine or violates any C++ Principles?
IShmWrapper.h
#pragma once
class IShmWrapper
{
public:
virtual bool writeToSharedMemory() = 0;
virtual bool readFromSharedMemory() = 0;
};
ShmWrapper.h
#include "IShmWrapper.h"
class ShmWrapper : public IShmWrapper
{
public:
bool writeToSharedMemory() override; //Write operation on shared memory
bool readFromSharedMemory() override;//Read operation on shared memory
};
ShmWrapper.cpp
#include "ShmWrapper.h"
bool ShmWrapper::writeToSharedMemory()
{
//Write operation on shared memory
}
bool ShmWrapper::readFromSharedMemory()
{
//Read operation on shared memory
}
ShmUserA.h
#include "IShmWrapper.h"
#include <memory>
class ShmUserA
{
private:
std::shared_ptr<IShmWrapper> m_shmWrapperA;
public:
ShmUserA(std::shared_ptr<IShmWrapper> shmWrapper);
};
ShmUserA.cpp
#include "ShmUserA.h"
ShmUserA::ShmUserA(std::shared_ptr<IShmWrapper> shmWrapper)
: m_shmWrapperA(std::move(shmWrapper))
{
// Do Additional initialization
}
ShmUserB.h
#include "IShmWrapper.h"
#include <memory>
class ShmUserB
{
private:
std::shared_ptr<IShmWrapper> m_shmWrapperB;
public:
ShmUserB(std::shared_ptr<IShmWrapper> shmWrapper);
};
ShmUserB.cpp
#include "ShmUserB.h"
ShmUserB::ShmUserB(std::shared_ptr<IShmWrapper> shmWrapper)
: m_shmWrapperB(std::move(shmWrapper))
{
// Do Additional initialization
}
Main.cpp
#include<iostream>
#include<IShmWrapper.h>
#include<ShmWrapper.h>
#include<ShmUserA.h>
#include<ShmUserB.h>
int main()
{
std::shared_ptr<IShmWrapper> shmInstance = std::make_shared<ShmWrapper>();
std::unique_ptr<ShmUserA> shmUserA = std::make_unique<ShmUserA>(shmInstance);
std::unique_ptr<ShmUserB> shmUserB = std::make_unique<ShmUserB>(shmInstance);
while(1)
{
//Do Processing of data for incoming requests
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
