I had been doing dependency injection using raw pointers and I decided to convert my code to use shared_ptr. This works but I'm wondering if I could use unique_ptr instead? In my example below, MyClass would manage the lifetime of the credit card service.
class PaymentProcessor
{
PaymentProcessor(?? creditCardService):
:creditCardService_(creditCardService)
{
}
private:
CreditCardService *creditCardService_;
}
class MyClass
{
public:
void DoIt()
{
creditCardService_.reset(new VisaCardService());
PaymentProcessor pp(creditCardService_);
pp.ProcessPayment();
}
private:
std::unique_ptr<CreditCardService> creditCardService_;
}
Can you pass a unique_ptr to another class where the other class is just "using" the pointer (without owning it??)? If so is this a good idea and what should the type of the parameter be in the constructor for PaymentProcessor?
UPDATE
In the example as shown above I can alternatively create a VisaCardService variable on the stack and have the PaymentProcessor constructor take this as a reference parameter. This seems to be the recommended C++ practice. However, in the case where the concrete type of creditCardService_ is not known until runtime (e.g., the user chooses the particular Credit Card Service to use at runtime), is using std::unique_ptr with references the best solution?
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
class A{
public:
void AddObject(MsgType msg){
msg_queue.push_back(msg);
}
private:
std::queue<MsgType> msg_queue;
}
I have this class A and its method AddObject(). There are 2 types of clients for this class. First type is where they get only boost::sharedPtr<MsgType> and other client has std::shared_ptr<MsgType> or const MsgType&.
What should be signature of AddObject() so that I can avoid conversion or making copy here. If I use AddObject(MsgType msg) then I will have to call from client side:
boost::shared_ptr<MsgType> msg;
AddObject(std::move(*msg));
or
std::shared_ptr<MsgType> msg;
AddObject(std::move(*msg));
and I can use std::move() in AddObject() to store it in queue.
Considering performance, what should be my API here?
Size of MsgType is around 1.4 MB which is protobuf message. For protobuf move costructors are very costly. So looks like I cannot use std::move here.
The way you have originally written AddObject(), it makes no assumptions about the ownership of the input MsgType. It doesn't know, or care, how the MsgType is allocated, or who should own it. In that scenario, the only valid thing you can do is make a copy for yourself, which is what you currently do.
If you want AddObject() to take ownership without making a copy, then AddObject() needs to be explicit about how it expects ownership to be managed. You express ownership semantics in one of two ways:
require exclusive ownership by using std::unique_ptr (or boost::unique_ptr):
class A{
public:
void AddObject(std::unique_ptr<MsgType> msg){
msg_queue.push(std::move(*msg));
}
private:
std::queue<MsgType> msg_queue;
};
Or better:
class A{
public:
void AddObject(std::unique_ptr<MsgType> msg){
msg_queue.push(std::move(msg));
}
private:
std::queue<std::unique_ptr<MsgType>> msg_queue;
};
share ownership by using std::shared_ptr (or boost::shared_ptr):
class A{
public:
void AddObject(std::shared_ptr<MsgType> &msg){
msg_queue.push(msg);
}
private:
std::queue<std::shared_ptr<MsgType>> msg_queue;
};
Otherwise, all you can really do is std::move() the contents of the input MsgType, and then let the caller worry about deallocating the MsgType later on:
class A{
public:
void AddObject(MsgType &msg){
msg_queue.push(std::move(msg));
}
private:
std::queue<MsgType> msg_queue;
};
However, in your situation, this last option is probably not very viable since you claim that moving a protobuf object is costly. In that case, you should move around just a pointer to a protobuf object rather than moving around the object itself. That is where (std|boost)::unique_ptr and (std|boost)::shared_ptr come into play.
If you want to code your class to support both std and boost smart pointers, then you will have to either overload AddObject() for each type, or give it a template parameter that you can specialize on as needed.
After publicly inheriting enable_shared_from_this and initialzing the object of class, while calling another function of that class, i can still see empty weak pointer of enable_shared_from_this_class while debugging in Visual Studio.
All existing questions are due to either privately inheriting from enable_shared_from_this or calling weak_from_this in constructor. This is not the case for me. I am currently using c++ catch framework to test this scenario in visual studio debugger. In Initialize function, i can see, that weak_ptr of this object is empty.
header File :
template <typename T>
class IInfo
public:
IInfo()
{}
virtual ~IInfo()
{}
virtual bool RegisterForChange(FUNC_PTR<T> Callback, std::weak_ptr<T>) = 0;
};
template <typename T>
class Info : public IInfo<T>, public std::enable_shared_from_this<Info<T>>
{
public:
Info() {}
~Info() {}
virtual bool RegisterForChange(FUNC_PTR<T> Callback, std::weak_ptr<T> callerContext) override
{
//Some code
_callerContext = callerContext;
}
private:
std::weak_ptr<T> _callerContext;
};
class Env : public std::enable_shared_from_this<Env>
{
public:
Env();
bool Initialize();
static void func(/ some arguments / );
private:
std::shared_ptr<Info<Env>>_spInfo;
//other variables
}
Cpp File :
Env::Env() : _spInfo() // + other variables in initializer list
{
_spInfo = std::make_shared<Info<Env>>();
}
bool Env::Initialize()
{
_spInfo->RegisterForChange(FUNC_PTR<Env>func, this->weak_from_this());
}
TEST CASE : (used cpp catch framework)
Env env;
env.Initialize();
EDIT:
As per comments , asking it correcty, the Env module will be managed by a plugin which will create a unique_ptr and call Initialize.
Something like:
template<typename T>
std::unique_ptr<T> BringUp()
{
std::unique_ptr<T> ptr(std::make_unique<T>());
if (ptr && ptr->Initialize())
return std::move(ptr);
}
std::unique_ptr<Env> _envPtr;
_envPtr = BringUp<Env>();
I still face the same issue.
How shall i manage Env in this case?
Your construction code is still wrong. For shared_from_this to work, the object's lifetime has to be managed by shared pointers. First you tried managing it by scope and then you tried managing it with a unique pointer. Neither of those will work.
The point of shared_from_this is to allow an object's lifetime to be extended by code that needs to extend it. For that to work, the object's lifetime has to be managed by some structure that makes it possible for objects to extend its life. A scope can't do that because when the scope ends the object's memory is released. A unique_ptr can't do that because only one pointer to the object can exist at any time, so there's no way to extend its life as that would require two pointers (one would have to already exist or it would be dead and the one extending its life would be another).
Construct the Env object using std::make_shared and store a std::shared_ptr to it.
template<typename T>
std::shared_ptr<T> BringUp()
{
std::shared_ptr<T> ptr(std::make_shared<T>());
if (ptr && ptr->Initialize())
return std::move(ptr);
}
std::shared_ptr<Env> _envPtr;
_envPtr = BringUp<Env>();
I'm writing a C++/CLI class that needs to hold on to CComPtr for the duration of its lifefime, e.g.
public ref class MyClass
{
public:
MyClass()
{
CComPtr<ISomeType> pSomeType;
// init someType;
m_pSomeType = pSomeType;
}
private:
CComPtr<ISomeType> m_pSomeType;
void DoSomething()
{
m_pSomeType->DoSomething();
}
}
However this doesn't compile as mixed types are not supported - the solution is to use an AutoPtr. I still need reference counting and so this is what I came up with.
public ref class MyClass
{
public:
MyClass()
{
CComPtr<ISomeType> pSomeType;
// init someType;
m_pSomeType = new CComPtr<ISomeType>(pSomeType);
}
private:
AutoPtr<CComPtr<ISomeType>> m_pSomeType;
void DoSomething()
{
CComPtr<ISomeType> pSomeType = *m_pSomeType.GetPointer();
pSomeType->DoSomething();
}
}
This looks nasty to me, and I also suspect that its wrong in some way (I come from a C# background so I'm kind of learning a lot of this as I go).
How should I "store" a CComPtr as a member of a C++/CLR class?
I've made a smart pointer that might help you. It can't be used to manage COM pointers directly, but it can be used to hold a CComPtr inside a managed class.
scoped_ptr for C++/CLI (ensure managed object properly frees owned native object)
Please respect the license requirements if you choose to use it (commercial use is not prohibited, but you must give credit).
Also, you can write
(*m_pSomeType)->DoSomething();
instead of copying the CComPtr (which has to update the reference count).
Besides that, I would use the ctor-initializer-list instead of assignment in the constructor.
MyClass()
: m_pSomeType(new CComPtr<ISomeType>)
{
}
If you want to compile managed and unmanaged code seperately then here is a link.
Using this you can retain flavour of both.
I have a framework function which expects an object and a member function pointer (callback), like this:
do_some_work(Object* optr, void (Object::*fptr)()); // will call (optr->*fptr)()
How can I pass a lambda expression to it? Want to do somethink like this:
class MyObject : public Object
{
void mystuff()
{
do_some_work(this, [](){ /* this lambda I want to pass */ });
}
};
The meaning of it all is to not clutter the interface of MyObject class with callbacks.
UPD
I can improve do_some_work in no way because I don't control framework and because actually it isn't one function, there're hundreds of them. Whole framework is based on callbacks of that type. Common usage example without lambdas:
typedef void (Object::*Callback)();
class MyObject : public Object
{
void mystuff()
{
do_some_work(this, (Callback)(MyClass::do_work));
}
void do_work()
{
// here the work is done
}
};
SOLUTION Here's my solution based on Marcelo's answer:
class CallbackWrapper : public Object
{
fptr fptr_;
public:
CallbackWrapper(void (*fptr)()) : fptr_(fptr) { }
void execute()
{
*fptr_();
}
};
class MyObject : public Object
{
void mystuff()
{
CallbackWrapper* do_work = new CallbackWrapper([]()
{
/* this lambda is passed */
});
do_some_work(do_work, (Callback)(CallbackWrapper::execute));
}
};
Since we create the CallbackWrapper we can control it's lifetime for the cases where the callback is used asynchonously. Thanks to all.
This is impossible. The construct (optr->*fptr)() requires that fptr be a pointer-to-member. If do_some_work is under your control, change it to take something that's compatible with a lambda function, such as std::function<void()> or a parameterised type. If it's a legacy framework that isn't under your control, you may be able to wrap it, if it's a function template, e.g.:
template <typename Object>
do_some_work(Object* optr, void (Object::*fptr)());
Then, you can implement a wrapper template:
template <typename F>
void do_some_work(F f) {
struct S {
F f;
S(F f) : f(f) { }
void call() { f(); delete this; }
};
S* lamf = new S(f);
do_some_work(lamf, &S::call);
}
class MyObject // You probably don't need this class anymore.
{
void mystuff()
{
do_some_work([](){ /* Do your thing... */ });
}
};
Edit: If do_some_work completes asynchronously, you must allocate lamf on the heap. I've amended the above code accordingly, just to be on the safe side. Thanks to #David Rodriguez for pointing this out.
There are deeper problems with the approach that you are trying to take than the syntactical mismatch. As DeadMG suggests, the best solution is to improve the interface of do_some_work to take a functor of some sort (std::function<void()> in C++11 or with boost, or even a generic F on which operator() is called.
The solution provided by Marcelo solves the syntactical mismatch, but because the library takes the first element by pointer, it is the responsibility of the caller to ensure that the object will be alive when the callback is executed. Assuming that the callback is asynchronous, the problem with his solution (and other similar alternatives) is that the object can potentially be destroyed before the callback is executed, causing undefined behavior.
I would suggest that you use some form of plimp idiom, where the goal in this case would be to hide the need for callbacks (because the rest of the implementation might not need to be hidden you could use just another class to handle the callbacks but store it by value, if you don't want do have to dynamically allocate more memory):
class MyClass;
class MyClassCallbacks {
MyClass* ptr;
public:
MyClassCallbacks( MyClass* ptr ) : ptr(ptr) {}
// callbacks that execute code on `ptr`
void callback1() {
// do some operations
// update *ptr
}
};
class MyClass {
MyClassCallbacks callbackHandler;
public:
void mystuff() {
do_some_work( &callbackHandler, &MyClassHandler::callback1 );
}
};
In this design, the two classes are separated but represent a unique single entity, so it is fine to add a friend declaration and let MyClassCallbacks access the internal data in MyClass (both of them are one single entity, divided only to provide a cleaner interface, but coupling is already high, so adding the extra coupling requiered by friend is no problem).
Because there is a 1-1 relationship between MyClass and MyClassCallbacks instances, their lifetimes are bound and there would be no lifetime issues, except during destruction. During destruction you must ensure that there is no callback registered that can kick in while the MyClass object is being destroyed.
Since you are at it, you might want to walk the extra mile and do a proper pimpl: move all of the data and implementation into a different type that is held by pointer, and offer a MyClass that stores a pointer and offers just the public functions, implemented as forwarders to the pimpl object. This could be somehow tricky as you are using inheritance, and the pimpl idiom is a bit cumbersome to implement on type hierarchies (if you need to extend MyClass, deriving from Object could be done in the pimpl object, rather than the interface type).
I don't think you can do that. Your do_some_work() is declared to accept pointer to methods of class Object, so such should be provided. Otherwise optr->*fptr is invalid since the lambda is not member of Object. Probably you should try using std::function and adding the needed members of Object in its closure.
You must use std::function<void()>. Both function and member function pointers are highly unsuited to being callbacks.
I have a class messenger which relies on a printer instance. printer is a polymorphic base class and the actual object is passed to the messenger in the constructor.
For a non-polymorphic object, I would just do the following:
class messenger {
public:
messenger(printer const& pp) : pp(pp) { }
void signal(std::string const& msg) {
pp.write(msg);
}
private:
printer pp;
};
But when printer is a polymorphic base class, this no longer works (slicing).
What is the best way to make this work, considering that
I don’t want to pass a pointer to the constructor, and
The printer class shouldn’t need a virtual clone method (= needs to rely on copy construction).
I don’t want to pass a pointer to the constructor because the rest of the API is working with real objects, not pointers and it would be confusing / inconsistent to have a pointer as an argument here.
Under C++0x, I could perhaps use a unique_ptr, together with a template constructor:
struct printer {
virtual void write(std::string const&) const = 0;
virtual ~printer() { } // Not actually necessary …
};
struct console_printer : public printer {
void write(std::string const& msg) const {
std::cout << msg << std::endl;
}
};
class messenger {
public:
template <typename TPrinter>
messenger(TPrinter const& pp) : pp(new TPrinter(pp)) { }
void signal(std::string const& msg) {
pp->write(msg);
}
private:
std::unique_ptr<printer> pp;
};
int main() {
messenger m((console_printer())); // Extra parens to prevent MVP.
m.signal("Hello");
}
Is this the best alternative? If so, what would be the best way in pre-0x? And is there any way to get rid of the completely unnecessary copy in the constructor? Unfortunately, moving the temporary doesn’t work here (right?).
There is no way to clone polymorphic object without a virtual clone method. So you can either:
pass and hold a reference and ensure the printer is not destroyed before the messenger in the code constructing messenger,
pass and hold a smart pointer and create the printer instance with new,
pass a reference and create printer instance on the heap using clone method or
pass a reference to actual type to a template and create instance with new while you still know the type.
The last is what you suggest with C++0x std::unique_ptr, but in this case C++03 std::auto_ptr would do you exactly the same service (i.e. you don't need to move it and they are otherwise the same).
Edit: Ok, um, one more way:
Make the printer itself a smart pointer to the actual implementation. Than it's copyable and polymorphic at the same time at the cost of some complexity.
Expanding the comment into a proper answer...
The primary concern here is ownership. From you code, it is appears that each instance of messenger owns its own instance of printer - but infact you are passing in a pre-constructed printer (presumably with some additional state), which you need to then copy into your own instance of printer. Given the implied nature of the object printer (i.e. to print something), I would argue that the thing to which is it is printing is a shared resource - in that light, it makes no sense for each messenger instance to have it's own copy of printer (for example, what if you need to lock to access to std::cout)?
From a design point of view, what messenger needs on construction is actually really a pointer to some shared resource - in that light, a shared_ptr (better yet, a weak_ptr) is a better option.
Now if you don't want to use a weak_ptr, and you would rather store a reference, think about whether you can couple messenger to the type of printer, the coupling is left to the user, you don't care - of course the major drawback of this is that messenger will not be containable. NOTE: you can specify a traits (or policy) class which the messenger can be typed on and this provides the type information for printer (and can be controlled by the user).
A third alternative is if you have complete control over the set of printers, in which case hold a variant type - it's much cleaner IMHO and avoids polymorphism.
Finally, if you cannot couple, you cannot control the printers, and you want your own instance of printer (of the same type), the conversion constructor template is the way forward, however add a disable_if to prevent it being called incorrectly (i.e. as normal copy ctor).
All-in-all, I would treat the printer as a shared resource and hold a weak_ptr as frankly it allows better control of that shared resource.
Unfortunately, moving the temporary doesn’t work here (right?).
Wrong. To be, uh, blunt. This is what rvalue references are made for. A simple overload would quickly solve the problem at hand.
class messenger {
public:
template <typename TPrinter>
messenger(TPrinter const& pp) : pp(new TPrinter(pp)) { }
template <typename TPrinter>
messenger(TPrinter&& pp) : pp(new TPrinter(std::move(pp))) { }
void signal(std::string const& msg) {
pp->write(msg);
}
private:
std::unique_ptr<printer> pp;
};
The same concept will apply in C++03, but swap unique_ptr for auto_ptr and ditch the rvalue reference overload.
In addition, you could consider some sort of "dummy" constructor for C++03 if you're OK with a little dodgy interface.
class messenger {
public:
template <typename TPrinter>
messenger(TPrinter const& pp) : pp(new TPrinter(pp)) { }
template<typename TPrinter> messenger(const TPrinter& ref, int dummy)
: pp(new TPrinter())
{
}
void signal(std::string const& msg) {
pp->write(msg);
}
private:
std::unique_ptr<printer> pp;
};
Or you could consider the same strategy that auto_ptr uses for "moving" in C++03. To be used with caution, for sure, but perfectly legal and doable. The trouble with that is that you're influencing all printer subclasses.
Why don't you want to pass a pointer or a smart pointer?
Anyway, if you're always initializing the printer member in the constructor you can just use a reference member.
private:
printer& pp;
};
And initialize in the constructor initialization list.
When you have a golden hammer everything looks like nails
Well, my latest golden hammer is type erasure. Seriously I would not use it, but then again, I would pass a pointer and have the caller create and inject the dependency.
struct printer_iface {
virtual void print( text const & ) = 0;
};
class printer_erasure {
std::shared_ptr<printer_iface> printer;
public:
template <typename PrinterT>
printer_erasure( PrinterT p ) : printer( new PrinterT(p) ) {}
void print( text const & t ) {
printer->print( t );
}
};
class messenger {
printer_erasure printer;
public:
messenger( printer_erasure p ) : printer(p) {}
...
};
Ok, arguably this and the solutions provided with a template are the exact same thing, with the only slight difference that the complexity of type erasure is moved outside of the class. The messenger class has its own responsibilities, and the type erasure is not one of them, it can be delegated.
How about templatizing the class messanger ?
template <typename TPrinter>
class messenger {
public:
messenger(TPrinter const& obj) : pp(obj) { }
static void signal(printer &pp, std::string const& msg) //<-- static
{
pp->write(msg);
}
private:
TPrinter pp; // data type should be template
};
Note that, signal() is made static. This is to leverage the virtual ability of class printer and to avoid generating a new copy of signal(). The only effort you have to make is, call the function like,
signal(this->pp, "abc");
Suppose you have other datatypes then pp which are not related to template type, then those can be moved to a non template base class and that base can be inherited by messenger. I am not describing in much details but, I wish the point should be clearer.