c++ get factory method to be thread safe - c++

i have this c++ simple factory method :
class Vehicle {
public:
virtual void printVehicle() = 0;
static Vehicle* Create(VehicleType type);
virtual ~Vehicle(){}
};
Vehicle* Vehicle::Create(VehicleType type) {
if (type == VT_TwoWheeler)
return new TwoWheeler();
else if (type == VT_ThreeWheeler)
return new ThreeWheeler();
else if (type == VT_FourWheeler)
return new FourWheeler();
else return NULL;
}
I want that this factory method will when called from more then 1 thread be protected and return New Object to the caller thread only . other threads will wait
in java i guess its something like :
synchronized (Vehicle .class) {
.. protected code ...
}
How can it done in c++14 ?

Related

A better way to call child method from parent object

I wish to call a child method in a perent method from a map that givied from a child's method. Basically the child gives the functions and the parent call them.
How can I use class child methods instead of static methods (see function 'login')? I try to call with pointers, but that didn't go so well.
And it is possible that the function 'optionsMap' would not create a new object every time the function is called, initialize the map only ones.
perent object:
typedef RequestResult(*handleRequestFunc)(IRequestHandler* self, RequestInfo what);
typedef std::map<unsigned char, handleRequestFunc> handleRequestFunc_map;
class IRequestHandler
{
public:
virtual handleRequestFunc_map optionsMap() = 0;
RequestResult handleRequest(RequestInfo requestInfo)
{
auto funcMap = this->optionsMap();
auto code = requestInfo.buffer.getCode();
auto func = funcMap.find(code);
if (func == funcMap.end())
{
// error
}
else
{
auto funcPointer = func->second;
return funcPointer(this, requestInfo);
}
}
};
child object:
class RequestHandlerFactory;
class LoginRequestHandler : public IRequestHandler
{
public:
RequestResult static login(IRequestHandler* self, RequestInfo what)
{
LoginRequestHandler* myself = (LoginRequestHandler*)(self);
// use myself
return RequestResult();
}
// Inherited via IRequestHandler
virtual handleRequestFunc_map optionsMap() override
{
handleRequestFunc_map returnMap;
returnMap[0] = &LoginRequestHandler::login; // function example
return returnMap;
}
}

c++ Dependency Injection Polymorphism

I have a question about best practices for dependency injection with polymorphic classes. I'm new to C++, so please forgive me if this is an obvious question. Say I have a class Runner, which needs to take in two objects, a Logger and a Worker. Logger is an abstract class with two children, say FileLogger and SocketLogger. Similarly, Worker is an abstract class with two children, say ApproximateWorker and CompleteWorker.
The Runner class will be created from main() and will create the Logger and Worker based on a config file or something similar. I've done a lot of reading on SO and other places, and the general sentiment seems to be to prefer stack allocated objects and pass them in by reference. I'm not quite sure how to manage dynamically creating the objects like this, however. If using heap-allocated objects, I could do something like:
Logger* log;
Worker* worker;
if (/*user wants a file logger*/ {
log = new FileLogger();
} else {
log = new SocketLogger();
}
if (/* user wants an approximate worker*/) {
worker = new ApproximateWorker();
} else {
worker = new CompleteWorker();
}
Runner runner = Runner(log, worker);
runner.run();
Because I'm just storing the pointers on the stack, I can handle the different cases for Logger and Worker independently. If using stack-allocated objects, the only thing I can think would be do to something like:
if (/*file logger and approx worker*/) {
FileLogger log();
ApproximateWorker worker();
Runner runner = Runner(log, worker);
} else if (/*file logger and complete worker*/) {
FileLogger log();
CompleteWorker worker();
Runner runner = Runner(log, worker);
} else if (/*socket logger and approx worker*/) {
SocketLogger log();
ApproximateWorker worker();
Runner runner = Runner(log, worker);
} else {
SocketLogger log();
CompleteWorker worker();
Runner runner = Runner(log, worker);
}
Obviously, with more than two objects to pass in, or more than two subclasses per object, this quickly becomes ridiculous. My understanding is that object slicing will prevent you from doing something similar to the first snippet.
Am I missing something obvious here? Or is this a case for using dynamic memory (with smart pointers of course)?
If Runner will use these objects in a polymorphic way (access derived objects via base class interfaces), you should pass pointers or references to it. There are pros and cons of variables on stack and on heap. There is no universal rule that one is preferred over the other.
One thing more, abstract factory pattern may suit your case. It separates WHAT(exact types of objects are used) from HOW(these objects are used). It's all about encapsulating the change.
// Factory.h
class tAbstractFactory
{
public:
virtual Logger* getLogger() = 0;
virtual Worker* getWorker() = 0;
};
template<typename loggerClass, typename workerClass>
class tConcreteFactory: public tAbstractFactory
{
public:
loggerClass* getLogger() { return new loggerClass; }
workerClass* getWorker() { return new workerClass; }
};
// Runner.h
class Runner
{
public:
Runner(tAbstractFactory &fa)
{
m_logger = fa.getLogger();
m_worker = fa.getWorker();
}
private:
Logger *m_logger;
Worker *m_worker;
};
// Factory.cpp
tAbstractFactory &getFactory(int sel)
{
if (sel == 1)
{
static tConcreteFactory<FileLogger, ApproximateWorker> fa;
return fa;
}
else if (sel == 2)
{
static tConcreteFactory<FileLogger, CompleteWorker> fa;
return fa;
}
else if (sel == 3)
{
static tConcreteFactory<SocketLogger, ApproximateWorker> fa;
return fa;
}
else
{
static tConcreteFactory<SocketLogger, CompleteWorker> fa;
return fa;
}
}
// Client.cpp
Runner runner(fac);
Edit:
At least two benefits I can see:
When you add a new case or change the type of concrete Logger/Worker, Client.cpp won't be affected. That said, you limit the change inside Factory.cpp so that the client logic(which actually uses the created objects) is unchanged.
Runner is programmed to only the factory interface. Clients depending on the Runner interface won't be affected by the change of Logger, Worker, etc.
Personally, it's totally OK not to use this pattern for a small code base. In a large project where there are lots of dependencies among classes/files, it will make a difference, both to the compilation time and scalability.
Shared or unique pointers can help, but you can still take references to the object as dependency injected variables.
You do need to make sure that you don't destroy the objects (logger, worker) before the runner. Dependency injection asks for factories. In this case I use a unique_ptr not for passing around ownership, but as a RAII safe handle to the abstract type.
#include <iostream>
#include <memory>
#include <exception>
struct Logger{
virtual void log() =0;
};
struct Logger1 : Logger {
void log() override { std::cout << " l1 " << std::endl;}
};
struct Logger2 : Logger {
void log() override { std::cout << " l2 " << std::endl;}
};
struct Logger3 : Logger {
void log() override { std::cout << " l3 " << std::endl;}
};
struct Worker{
virtual void work() =0;
};
struct Worker1 : Worker{
void work() override { std::cout << " w1 " << std::endl;}
};
struct Worker2 : Worker{
void work() override { std::cout << " w2 " << std::endl;}
};
struct Worker3 : Worker{
void work() override { std::cout << " w3 " << std::endl;}
};
struct Runner{
Runner(Worker& worker, Logger& logger): worker(worker),logger(logger) {};
Worker& worker;
Logger& logger;
void run(){
worker.work();
logger.log();
}
};
std::unique_ptr<Worker> mkUniqueWorker(int i){
switch (i) {
case 1: return std::make_unique<Worker1>() ;
case 2: return std::make_unique<Worker2>() ;
case 3: return std::make_unique<Worker3>() ;
case 4: throw std::runtime_error("unknown worker");
}
};
std::unique_ptr<Logger> mkUniqueLogger(int i){
switch (i) {
case 1: return std::make_unique<Logger1>() ;
case 2: return std::make_unique<Logger2>() ;
case 3: return std::make_unique<Logger3>() ;
case 4: throw std::runtime_error("unknown logger");
}
};
int main() {
auto worker = mkUniqueWorker(2);
auto logger = mkUniqueLogger(3);
Runner runner = Runner(*worker, *logger);
runner.run();
return 0;
}

Static member functions in C++

I was going through one of the examples of C++, for cloning of an object.
#ifndef CLIPBOARDSTACK_H
#define CLIPBOARDSTACK_H
#include <QStack>
#include "getEntity.h"
class clipboardStack
{
public:
static clipboardStack *instance()
{
if (!inst)
inst = new clipboardStack;
return inst;
}
void push(getEntity *entity)
{
clips.push(entity);
}
getEntity *pasteEntity()
{
if (clips.count() == 0)
return 0;
return clips.last();
}
getEntity *pop()
{
if (clips.count() == 0)
return 0;
return clips.pop();
}
bool isEmpty() const
{
return clips.empty();
}
private:
QStack<getEntity *> clips;
static clipboardStack *inst;
};
#endif // CLIPBOARDSTACK_H
where getEntity is:
#ifndef GETENTITY_H
#define GETENTITY_H
#include <QGraphicsItem>
class getEntity : public QObject, public QGraphicsItem
{
public:
getEntity(QObject *parent = 0) : QObject(parent) {}
virtual ~getEntity() {}
virtual getEntity *clone()
{
return 0;
}
};
#endif // GENTITY_H
But I couldn't get what exactly the line means.
What is the meaning of the line:
static clipboardStack *instance()
{
if (!inst)
inst = new clipboardStack;
return inst;
}
Can someone explain me what does above line exactly do, and the two classes in brief?
static clipboardStack *instance()
{
if (!inst)
inst = new clipboardStack;
return inst;
}
This is a code for singleton pattern. If there is no instance of class clipboardStack, then it would create it else it would return already created instance.
NOTE:- This implementation of singleton is not thread-safe.
static clipboardStack *instance()
{
if (!inst)
inst = new clipboardStack;
return inst;
}
This is singleton pattern, usually they write this pattern for having only one instance of the class at any point of time.
If there is no instance for the clipboardstack created. you just create one. next time when someone calls instance(), it delivers the same instance created before. No new instance gets created again.
I guess you have to initialize the clipboardstack pointer to NULL. Its a good programming practice. If you are in a debug mode this might point to uninitialized memory like 0xCDCDCD for instance, which is not null and everytime you call instance(), you will get 0xCDCDCD and you will end up crashing the program.

How to extend and use members of a superclass in c++?

I'm trying to code a class to handle joystick input (irrelevant), and being rusty on inheritance and new to c++ I'm having some confusion while trying to create a subclass of my joystick class. Here's my code
//superclass's .h
#ifndef JOYSTICKINPUT_H
#define JOYSTICKINPUT_H
#include "WPILib.h"
class JoystickInput {
public:
JoystickInput(Joystick*);
Joystick * joystick;
Victor * myVictor [3];
bool buttons [10];
bool buttonClicked(int id);
void testForActions();
};
#endif
And here's its definition
//superclass's .cpp
#include "JoystickInput.h"
JoystickInput::JoystickInput(Joystick * joy) {
joystick = joy;
for (int x = 0; x < 10; x++) {
buttons[x] = false;
}
}
bool JoystickInput::buttonClicked(int id) {
if (buttons[id] == false and joystick->GetRawButton(id) == true) {
buttons[id] = true;
return true;
} else if (buttons[id] == true and joystick->GetRawButton(id) == false) {
buttons[id] = false;
return false;
} else {
return false;
}
}
void JoystickInput::testForActions() {
}
Now I'm trying to extend this with a JoystickOne class, as its behavior is slightly different. To this end I created a JoystickOne.h and a JoystickOne.cpp
//Joystickone.h
#ifndef JOYSTICKONE_H
#define JOYSTICKONE_H
#include "WPILib.h"
#include "JoystickInput.h"
class JoystickOne : public JoystickInput {
public:
JoystickOne(Joystick*);
Joystick * joystick;
Victor * myVictor;
bool buttons [10];
bool buttonClicked(int id);
void testForActions();
};
#endif
And the .cpp
#include "JoystickOne.h"
#include "WPILib.h"
JoystickOne::JoystickOne(Joystick * joy) : JoystickInput(joy) {
//joystick = joy;
//myVictor = new Victor(1);
/*for (int x = 0; x < 10; x++) {
buttons[x] = false;
}*/
}
bool JoystickOne::buttonClicked(int id) {
if (buttons[id] == false and joystick->GetRawButton(id) == true) {
buttons[id] = true;
return true;
} else if (buttons[id] == true and joystick->GetRawButton(id) == false) {
buttons[id] = false;
return false;
} else {
return false;
}
}
void JoystickOne::testForActions() {
if (buttonClicked(1)) {
}
if (buttonClicked(2)) {
}
if (buttonClicked(3)) {
//myVictor->Set(.3);
}
if (buttonClicked(4)) {
}
}
My problem is that I'm not quite sure what's extraneous in the JoystickOne class. I come from Java, so I'm used to being able to just extend a superclass and automatically use all of its methods and members. I'm confused because of C++'s seperation into .h and .cpp files; from what I've learned by messing around I have to declare all variables and methods I wish to use, even if they're members of the superclass. I don't think I have to define method buttonClicked() twice, although I don't have a robot so I can't actually test that now.
Basically, I'm asking what I can cut out from the definition of the JoystickOne class, and how to do it. If any of you have advice on some good OOP practices in C++ feel free to share, or maybe even clear up some java-isms that I have.
Thanks!
You should mark methods that can be overridden as virtual in your base class. To override it in a derived class, simply re-define it in your derived class.
Example:
class Base{
public:
virtual void overrideThis() { std::cout << "Base" << std::end; }
void test() { std::cout << "Base::test()" << std::endl; }
};
class Derived : public Base{
public:
void overrideThis() { std::cout << "Derived" << std::endl; }
};
Now if you instantiate:
Derived d;
d.overrideThis(); // Will print 'Derived'
d.test(); // Will print 'Base::test()'
As for member variables. Private members defined in your base will class will NOT be available in your derived class. On the other hand, protected and public member variables will be accessible.
You need to use the virtual keyword to make your functions inheritable. Furthermore, you can declare functions such as
buttonClicked(int id) = 0;
This will be the equivalent of an abstract methods.
You should not need to redefine variables, they should be automatically inherited if public or protected. Also note that you should declare your destructors virtual at all times, otherwise inherited classes will not be able to delete their own stuff.
No you don't have to re-declare the attributes in your inherited/child class, so remove those. Generally make them private (usable by parent class only) or protected (usable by parent and child classes) not public. With your methods, only 're-declare' them (override) if they act differently in the child class, and make sure you declare them virtual in the parent class. Experimenting is good.. remove some stuff, add lots of print statements, and see how it behaves :) It's not SO different from Java* apart from the .h/.cpp thing.
*At the basic level

Scope issue while creating objects inside if statement if C++

This is supposed to be very basic.
Layout:
class handler {
public:
handler(Connection *conn) { connection = conn; }
virtual void handle() = 0;
};
class http_status : public handler {
public:
http_status(Connection *conn) : handler(conn) { }
void handle();
};
class http_photoserver : public handler {
public:
http_photoserver(Connection *conn) : handler(conn) { }
void handle();
};
Code:
void pick_and_handle() {
if (connection->http_header.uri_str != "/") {
http_photoserver handler(connection);
} else {
http_status handler(connection);
}
handler.handle();
}
This gives an error:
../handler.cpp:51:10: error: expected unqualified-id before ‘.’ token
I'm guessing because compiler doesn't know what handler is cause object is created inside an if statement. I need to pick a handler based on a condition, how do I do that?
Obviously this code works:
if (connection->http_header.uri_str != "/") {
http_photoserver handler(connection);
handler.handle();
} else {
http_status handler(connection);
handler.handle();
}
But doesn't look very sexy! Is it really the only way in c++?
Use a pointer so you get polymorphic behavior:
auto_ptr<handler> theHandler = (connection->http_header.uri_str != "/") ?
new http_photoserver(connection) :
new http_status(connection);
theHandler->handle();
Of course it's not the only way. But you may have to use pointers:
void pick_and_handle() {
unique_ptr<handler> http_handler;
if (connection->http_header.uri_str != "/")
http_handler.reset(new http_photoserver(connection));
else
http_handler.reset(new http_status(connection));
http_handler->handle();
}
(Instead of unique_ptr, you can use boost::scoped_ptr, shared_ptr, and auto_ptr also. But in this case, unique_ptr and boost::scoped_ptr are most appropriate.)
C++ can only do polymorphism in pointers and references. Note that with your code, the actual type of handler is not known till runtime. The only thing known is that it will be of one of the subtypes of handler, so you have to declare a pointer to use the polymorphism:
void pick_and_handle() {
std::auto_ptr<handler> h;
if (connection->http_header.uri_str != "/") {
h.reset(new http_photoserver(connection));
} else {
h.reset(new http_status(connection));
}
h->handle();
}
I use std::auto_ptr to assure the pointer will be automatically deleted when the function ends.
The object handler doesn't exist outside the scope in which its defined.
One solution could be runtime polymorphism, that is, define a base class and a virtual function in it, as:
struct base_handler
{
virtual void handle(Connection *conn) = 0; //interface
virtual ~base_handler() {} //must make it virtual!
};
struct http_photoserver : base_handler
{
virtual void handle(Connection *conn) {} //implementation
};
struct http_status : base_handler
{
virtual void handle(Connection *conn) {} //implementation
};
Then use it as:
base_handler *phander ;
if (connection->http_header.uri_str != "/") {
phandler = new http_photoserver(connection);
} else {
phandler = new http_status (connection);
}
phandler->handle();
//...
delete phandler;
Declare a pointer somewhere above that code, and then assign an object later in the if statement. Since they are inherited from the same class, OO teaches us that a child can replace a parent :) .
After that it should work.
Just don't forget to destruct! :)
Hope I helped.
If you go with the pointer approach like the others suggest you should also add a virtual destructor the base class.
This approach can be better expressed using a factory method. Just add a static function in your base class that accepts a connection and returns a (smart) pointer to a handler. Put the "pick" logic there.
If you don't want the pointer approach then the second version you posted is the one to use.