Consider the below class
class Forwarder : public Base
{
private:
Base* dest;
Forwarder* next;
public:
explicit Forwarder(Base* dest, Forwarder* next)
: dest(dest), next(next) {}
~Forwarder() {
if (next) delete next;
delete dest;
}
void DoStuff() {
if (next) next->DoStuff();
dest->Process();
}
};
Its purpose is to create a forwarding chain for events, so if DoStuff gets called at the base it will propagate throughout the chain, notifying others. I want to use this for sending output to various streams. Anyway, a typical way to create a chain would be like:
Forwarder f(new First, new Forwarder(new SomeOther, new Forwarder(new YouGetTheIdea, NULL)));
This is a really convenient way of constructing a chain, but it’s dangerous and vulnerable to memory leaks because the compiler can shuffle things around. Is there a safer way to construct chains like I’m wanting (preferably retaining the lean syntax)?
Instead of using
newexplicitly, use a function which returns a smart pointer, and make the constructors take in smart pointers.And then use it as so:
you could also use
unique_ptrinstead, if you implementmake_unique()(or equivalent factory methods)