Delegating object destruction - c++

I've found this class definition (T has to derive from TBase),
passResponsabilityToBarDestructor is not the actual name of the
function, sadly.
template<typename T>
class Foo
{
public:
Foo(const std::string& aName, Bar& aBar)
{
const TBase* myObj = static_cast<const TBase*>(new T);
NiceNameSpace::passResponsabilityToBarDestructor(aName, myObj, aBar);
}
virtual ~Foo() {}
};
I'm wondering if it is well designed.
When I write a class I tend to avoid delegating destruction since I
don't know if the delegated class (in this case Bar) is going to be modified
by someone not aware of the fact that passResponsabilityToBarDestructor has to call
a member function of aBar saving the pointer myObj somewhere and deleting it
when myObj get destroyed.
I would like to know:
if this class is well designed
if my design efforts (when I cannot use smart pointers I get headaches trying to
write classes destroying stuff in the same class constructing it) are a waste of time.

Delegation of destruction actually helps in many cases. I have come across code - where the cost of destruction is quite heavy, so the designers don't want to destroy the object during the call flow - instead delegate it to another thread level and delete it in background (ideally when system is not busy). In such cases, the garbage collector (in another thread) destroys the object.
This also sometimes used for quick switch of data (for cases of data refresh) and delete the old data at ease. I think it is a similar concept as in gc of Java.
Regarding as to whether this particular design is efficient/useful, may be if you add overall concept, it may help us to add some suggestion. Effectively, I have given some hint on second part of your question. HTH!

Related

Use of shared pointers in public interfaces

We have a pretty standard tree API using shared pointers that looks roughly like this (implementations omitted for brevity):
class node;
using node_ptr = std::shared_ptr<node>;
class node : public std::enable_shared_from_this<node> {
std::weak_ptr<node> parent;
std::vector<node_ptr> children;
public:
virtual ~node() = default;
virtual void do_something() = 0;
void add_child(node_ptr new_child);
void remove_child(node_ptr child);
node_ptr get_parent();
const std::vector<node_ptr>& get_children();
};
class derived_node : public node {
derived_node() = default;
public:
virtual void do_something() override;
static node_ptr create(/* args... */);
};
// More derived node types...
This works just fine and prevents nodes being leaked as you'd imagine. However, I've read on various other answers on SO that using std::shared_ptr in a public API like this is considered bad style and should be avoided.
Obviously this ventures into opinion-based territory, so a couple of concrete questions to avoid this question being closed :-)
Are there any well-known pitfalls to using shared_ptrs in interfaces like this, which we have so far been fortunate enough to avoid?
If so, is there a commonly-used (I hesitate to say "idiomatic") alternative formulation which avoids said pitfalls but still allows for simple memory management for users?
Thanks.
Its not bad style, it depends on your goals, and assumptions.
A few projects I've worked on with hard restraints required us to avoid shared_ptrs because we wanted to manage our own memory. So use of 3rd party libs that would require to use shared_ptrs are out.
Another reason you might wish to avoid shared_ptrs is that its somewhat opinionated. Some projects will wrap everything around it and just pretend its like having a GC language (Urg!). Other projects will treat shared_ptrs with a little more restraint, and only use shared_ptr's when it comes down to actually things that have shared ownership.
Most of the 3rd party API (certainly not all) I've worked with operate on the principle if you've allocated it, you destroy it. So long as your very clear about the ownership of the resource it doesn't cause too much issue.
std::shared_ptr is to manage ownership,
so prefer for print_tree function
void print_tree(const node& root); // no owner ship transfer
than
void print_tree(const std::shared_ptr<node>& root);
The later requires a shared_ptr, so may require a construction of a shared_ptr from the object. (whereas retrieving object from shared_ptr is a simple getter)
Now, for your getters, you have mainly the choice between
share_ptr, if you want to share ownership with user
weak_ptr, secure reference to internal
pointer/reference, insecure reference to internal.
By secure and insecure, I mean that if object is destroyed,
you may test that with weak_ptr, but not with simple pointer.
The security has some overhead though, so there is a trade-off.
If accessors are for local usage only and not to keep reference on it, pointer/reference may be a good option.
As example, std::vector::iterator are unusable once the vector is destroyed, so there are good for local usage but may be dangerous to keep iterator as reference (but possible).
Do you expect/allow that user keeps reference of a node but allow the root (or parent) to be destroyed ? what should happen to that node for user ?
For void add_child(node_ptr new_child);, you clearly take ownership. You may hide the shared_ptr if the node construct it child itself, something like
template <typename NodeType, typename...Ts>
std::weak_ptr<NodeType> add_child(Ts&&... args)
{
auto n = std::make_shared<NodeType>(std::forward<Ts>(args)...);
// or
// auto n = NodeType::create(std::forward<Ts>(args)...);
// Stuff as set parent and add to children vector
return n;
}
One reason this may be considered bad style may be the additional overhead involved in reference counting that is often (never say never) not actually needed in external APIs, since they often fall into one of two categories:
An API that receives a pointer, acts on it and returns it - a raw pointer will usually work better, since the function does not need to manage the pointer itself in any way
An API that manages the pointer, such as in your case - a std::unique_ptr will usually be a better fit, and it has 0 overhead.

What is the proper way to write C++ Setters for members which are pointers to other objects so that there are no memory leaks or crashes?

I have searched a lot on this. But may be I am not getting the phrasing right.
Consider,
Class A {};
Class B {
public:
A* getA();
void setA(A *aVarParam);
private:
A *aVar;
};
Now since aVar is a member variable of class B I want to ensure that it stays alive as long the corresponding object of class B exists.
So the options I see here are,
Make a deep copy of aVarParam and hold a pointer to it.
Use something like a Boost shared pointer.
Both of which seems either too much work or ugly syntax. Am I missing something here? Do all C++ programs use one of these 2 options?
More Explanation:
Ok many of you wanted to see an example of how I am using it. Actually I wanted a general purpose strategy kind of answer. Hence the original example. Here is the example I am trying to use:
#ifndef DBSCHEMA_H
#define DBSCHEMA_H
#include <string>
#include <vector>
#include "dbtable.h"
namespace models {
class DbSchema
{
public:
explicit DbSchema();
boost::shared_ptr<std::string> getSchemaName() const;
void setSchemaName(const boost::shared_ptr<std::string> schemaName);
std::vector<models::DbTable> getTableList() const;
void setTableList(const std::vector<models::DbTable> tableList);
private:
boost::shared_ptr<std::string> schemaName_;
std::vector<models::DbTable> tableList_;
};
}
#endif // DBSCHEMA_H
Here the class DbSchema is being used as a thin model which will direct the UI (A QT application). And there will be many Schema Builders which will actually communicate with different databases to fill the DBSchema objects which the UI will use.
I hope this clears up about what I am trying to achieve. I am not a C++ programmer. After programming Java, Objective-C, PHP and JavaScript for years, I am trying to satisfy an itch to write a "real C++" application.
For the sake of the question, I'll assume that you have a genuine reason for storing a pointer, rather than the object itself. However, if your real code is similar to the example, then there is no good reason for storing a pointer to a string.
The third option is to take ownership of the object. Before C++11, this was tricky to achieve without the danger of leaks or dangling pointers, but these days we have move semantics and unique_ptr, a smart pointer to handle single transferable ownership semantics.
#include <memory>
class B {
public:
void setA(std::unique_ptr<A> aVarParam) {
aVar = std::move(aVarParam);
}
private:
std::unique_ptr<A> aVar;
};
std::unique_ptr<A> myA(new A);
assert(myA); // we own the object
b.setA(std::move(myA)); // transfer ownership
assert(!myA); // we no longer own it
If you want B to own the object A then it is not clear
to a user who owns the object after a function like
A* getA();
who should delete the object?
even though there is additional syntax using a shared_ptr
would make it clear to the user of your class who owns the
object.
std::shared_ptr<A> getA();
If you otoh want to pass the object along to somebody else
use std::unique_ptr instead.
there is not much overhead at all adding this and it makes
your code easier to read.
I think the first question you need to answer is a matter of conception.
Who's supposed to own the resource, and who's using it.
If these two are the same, a unique_ptr seems appropriate, if not, the shared_ptr/weak_ptr could be appropriate, but again, without knowing more about your whole problem, seems hard to give a definite answer.
For example, if your class is merely using the resource without owning it, the resource should be stored with a shared_ptr somewhere, and your class should only hold a weak_ptr to it, and lock it only when it wants to use it, and be prepared to handle the case where the resource has been deleted (if that should happen).
edit: after seeing your edit
Seeing your code like that, I don't see why you would need a pointer, just use a classic std::string and all will be fine... (unless I'm missing something, but that raises the question: why a pointer?)

Is there a way to force an object to be created on the heap with shared_ptr?

i was wondering if it is possible to force an object to be created on the heap by creating a private/protected desctuctor and by using shared_ptrs to ensure an automatic resource managment (the RAII features of a shared_ptr) at the same time.
Can that be done in a different way maybe?
The reason i ask that, is because from what i heard(didnt look at that yet) at the STL there are no virtual descructors,so there is no way to ensure safe destruction other than...shared_ptr?
And if so,there is no way to force the object to the heap since shared_ptr is trying to access the destuctor.
Anyway to bypass these limitations?
C++ is a language that puts the correctness of the code in the hand of the programmer. Trying to alter that via some convoluted methods typically leads to code that is hard to use or that doesn't work very well. Forcing the hand of the programmer so that (s)he has to create an object on the heap even if that's not "right" for that particular situation is just bad. Let the programmer shoot him-/herself in the foot if he wants to.
In larger projects, code should be reviewed by peers (preferably at least sometimes by more senior staff) for correctness and that it follows the coding guidelines of the project.
I'm not entirely sure how "virtual destructors" relate to "safe destruction" and "shared pointers" - these are three different concepts that are not very closely related - virtual destructors are needed when a class is used as a base-class to derive a new class. STL objects are not meant to be derived from [as a rule, you use templates OR inheritance, although they CAN be combined, it gets very complicated very quickly when you do], so there is no need to use virtual destructors in STL.
If you have a class that is a baseclass, and the storage is done based on pointers or references to the baseclass, then you MUST have virtual destructors - or don't use inheritance.
"safe destruction", I take it, means "no memory leaks" [rather than "correct destruction", which can of course also be a problem - and cause problems with memory leaks]. For a large number of situations, this means "don't use pointers to the object in the first place". I see a lot of examples here on SO where the programmer is calling new for absolutely no reason. vector<X>* v = new vector<X>; is definitely a "bad smell" (Just like fish or meat, something is wrong with the code if it smells bad). And if you are calling new, then using shared pointer, unique pointer or some other "wrapping" is a good idea. But you shouldn't force that concept - there are occasionally good reasons NOT to do that.
"shared pointer" is a concept to "automatically destroy the object when it is no longer in use", which is a useful technique to avoid memory leaks.
Now that I have told you NOT to do this, here's one way to achieve it:
class X
{
private:
int x;
X() : x(42) {};
public:
static shared_ptr<X> makeX() { return make_shared<X>(); }
};
Since the constructor is private, the "user" of the class can't call "new" or create an object of this kind. [You probably also want to put the copy constructor and assignment operator in private or use delete to prevent them from being used].
However, I still think this is a bad idea in the first place.
The answer by Mats is indeed wrong. The make_shared needs a public constructor.
However, the following is valid:
class X
{
private:
int x;
X() : x( 42 ) {};
public:
static std::shared_ptr<X> makeX()
{
return std::shared_ptr<X>( new X() );
}
};
I don't like to use the new keyword, but in this case, it is the only way.

delete this & private destructor

I've been thinking about the possible use of delete this in c++, and I've seen one use.
Because you can say delete this only when an object is on heap, I can make the destructor private and stop objects from being created on stack altogether. In the end I can just delete the object on heap by saying delete this in a random public member function that acts as a destructor. My questions:
1) Why would I want to force the object to be made on the heap instead of on the stack?
2) Is there another use of delete this apart from this? (supposing that this is a legitimate use of it :) )
Any scheme that uses delete this is somewhat dangerous, since whoever called the function that does that is left with a dangling pointer. (Of course, that's also the case when you delete an object normally, but in that case, it's clear that the object has been deleted). Nevertheless, there are somewhat legitimate cases for wanting an object to manage its own lifetime.
It could be used to implement a nasty, intrusive reference-counting scheme. You would have functions to "acquire" a reference to the object, preventing it from being deleted, and then "release" it once you've finished, deleting it if noone else has acquired it, along the lines of:
class Nasty {
public:
Nasty() : references(1) {}
void acquire() {
++references;
}
void release() {
if (--references == 0) {
delete this;
}
}
private:
~Nasty() {}
size_t references;
};
// Usage
Nasty * nasty = new Nasty; // 1 reference
nasty->acquire(); // get a second reference
nasty->release(); // back to one
nasty->release(); // deleted
nasty->acquire(); // BOOM!
I would prefer to use std::shared_ptr for this purpose, since it's thread-safe, exception-safe, works for any type without needing any explicit support, and prevents access after deleting.
More usefully, it could be used in an event-driven system, where objects are created, and then manage themselves until they receive an event that tells them that they're no longer needed:
class Worker : EventReceiver {
public:
Worker() {
start_receiving_events(this);
}
virtual void on(WorkEvent) {
do_work();
}
virtual void on(DeleteEvent) {
stop_receiving_events(this);
delete this;
}
private:
~Worker() {}
void do_work();
};
1) Why would I want to force the object to be made on the heap instead of on the stack?
1) Because the object's lifetime is not logically tied to a scope (e.g., function body, etc.). Either because it must manage its own lifespan, or because it is inherently a shared object (and thus, its lifespan must be attached to those of its co-dependent objects). Some people here have pointed out some examples like event handlers, task objects (in a scheduler), and just general objects in a complex object hierarchy.
2) Because you want to control the exact location where code is executed for the allocation / deallocation and construction / destruction. The typical use-case here is that of cross-module code (spread across executables and DLLs (or .so files)). Because of issues of binary compatibility and separate heaps between modules, it is often a requirement that you strictly control in what module these allocation-construction operations happen. And that implies the use of heap-based objects only.
2) Is there another use of delete this apart from this? (supposing that this is a legitimate use of it :) )
Well, your use-case is really just a "how-to" not a "why". Of course, if you are going to use a delete this; statement within a member function, then you must have controls in place to force all creations to occur with new (and in the same translation unit as the delete this; statement occurs). Not doing this would just be very very poor style and dangerous. But that doesn't address the "why" you would use this.
1) As others have pointed out, one legitimate use-case is where you have an object that can determine when its job is over and consequently destroy itself. For example, an event handler deleting itself when the event has been handled, a network communication object that deletes itself once the transaction it was appointed to do is over, or a task object in a scheduler deleting itself when the task is done. However, this leaves a big problem: signaling to the outside world that it no longer exists. That's why many have mentioned the "intrusive reference counting" scheme, which is one way to ensure that the object is only deleted when there are no more references to it. Another solution is to use a global (singleton-like) repository of "valid" objects, in which case any accesses to the object must go through a check in the repository and the object must also add/remove itself from the repository at the same time as it makes the new and delete this; calls (either as part of an overloaded new/delete, or alongside every new/delete calls).
However, there is a much simpler and less intrusive way to achieve the same behavior, albeit less economical. One can use a self-referencing shared_ptr scheme. As so:
class AutonomousObject {
private:
std::shared_ptr<AutonomousObject> m_shared_this;
protected:
AutonomousObject(/* some params */);
public:
virtual ~AutonomousObject() { };
template <typename... Args>
static std::weak_ptr<AutonomousObject> Create(Args&&... args) {
std::shared_ptr<AutonomousObject> result(new AutonomousObject(std::forward<Args>(args)...));
result->m_shared_this = result; // link the self-reference.
return result; // return a weak-pointer.
};
// this is the function called when the life-time should be terminated:
void OnTerminate() {
m_shared_this.reset( NULL ); // do not use reset(), but use reset( NULL ).
};
};
With the above (or some variations upon this crude example, depending on your needs), the object will be alive for as long as it deems necessary and that no-one else is using it. The weak-pointer mechanism serves as the proxy to query for the existence of the object, by possible outside users of the object. This scheme makes the object a bit heavier (has a shared-pointer in it) but it is easier and safer to implement. Of course, you have to make sure that the object eventually deletes itself, but that's a given in this kind of scenario.
2) The second use-case I can think of ties in to the second motivation for restricting an object to be heap-only (see above), however, it applies also for when you don't restrict it as such. If you want to make sure that both the deallocation and the destruction are dispatched to the correct module (the module from which the object was allocated and constructed), you must use a dynamic dispatching method. And for that, the easiest is to just use a virtual function. However, a virtual destructor is not going to cut it because it only dispatches the destruction, not the deallocation. The solution is to use a virtual "destroy" function that calls delete this; on the object in question. Here is a simple scheme to achieve this:
struct CrossModuleDeleter; //forward-declare.
class CrossModuleObject {
private:
virtual void Destroy() /* final */;
public:
CrossModuleObject(/* some params */); //constructor can be public.
virtual ~CrossModuleObject() { }; //destructor can be public.
//.... whatever...
friend struct CrossModuleDeleter;
template <typename... Args>
static std::shared_ptr< CrossModuleObject > Create(Args&&... args);
};
struct CrossModuleDeleter {
void operator()(CrossModuleObject* p) const {
p->Destroy(); // do a virtual dispatch to reach the correct deallocator.
};
};
// In the cpp file:
// Note: This function should not be inlined, so stash it into a cpp file.
void CrossModuleObject::Destroy() {
delete this;
};
template <typename... Args>
std::shared_ptr< CrossModuleObject > CrossModuleObject::Create(Args&&... args) {
return std::shared_ptr< CrossModuleObject >( new CrossModuleObject(std::forward<Args>(args)...), CrossModuleDeleter() );
};
The above kind of scheme works well in practice, and it has the nice advantage that the class can act as a base-class with no additional intrusion by this virtual-destroy mechanism in the derived classes. And, you can also modify it for the purpose of allowing only heap-based objects (as usually, making constructors-destructors private or protected). Without the heap-based restriction, the advantage is that you can still use the object as a local variable or data member (by value) if you want, but, of course, there will be loop-holes left to avoid by whoever uses the class.
As far as I know, these are the only legitimate use-cases I have ever seen anywhere or heard of (and the first one is easily avoidable, as I have shown, and often should be).
The general reason is that the lifetime of the object is determined by some factor internal to the class, at least from an application viewpoint. Hence, it may very well be a private method which calls delete this;.
Obviously, when the object is the only one to know how long it's needed, you can't put it on a random thread stack. It's necessary to create such objects on the heap.
It's generally an exceptionally bad idea. There are a very few cases- for example, COM objects have enforced intrusive reference counting. You'd only ever do this with a very specific situational reason- never for a general-purpose class.
1) Why would I want to force the object to be made on the heap instead of on the stack?
Because its life span isn't determined by the scoping rule.
2) Is there another use of delete this apart from this? (supposing that this is a legitimate use of it :) )
You use delete this when the object is the best placed one to be responsible for its own life span. One of the simplest example I know of is a window in a GUI. The window reacts to events, a subset of which means that the window has to be closed and thus deleted. In the event handler the window does a delete this. (You may delegate the handling to a controller class. But the situation "window forwards event to controller class which decides to delete the window" isn't much different of delete this, the window event handler will be left with the window deleted. You may also need to decouple the close from the delete, but your rationale won't be related to the desirability of delete this).
delete this;
can be useful at times and is usually used for a control class that also controls the lifetime of another object. With intrusive reference counting, the class it is controlling is one that derives from it.
The outcome of using such a class should be to make lifetime handling easier for users or creators of your class. If it doesn't achieve this, it is bad practice.
A legitimate example may be where you need a class to clean up all references to itself before it is destructed. In such a case, you "tell" the class whenever you are storing a reference to it (in your model, presumably) and then on exit, your class goes around nulling out these references or whatever before it calls delete this on itself.
This should all happen "behind the scenes" for users of your class.
"Why would I want to force the object to be made on the heap instead of on the stack?"
Generally when you force that it's not because you want to as such, it's because the class is part of some polymorphic hierarchy, and the only legitimate way to get one is from a factory function that returns an instance of a different derived class according to the parameters you pass it, or according to some configuration that it knows about. Then it's easy to arrange that the factory function creates them with new. There's no way that users of those classes could have them on the stack even if they wanted to, because they don't know in advance the derived type of the object they're using, only the base type.
Once you have objects like that, you know that they're destroyed with delete, and you can consider managing their lifecycle in a way that ultimately ends in delete this. You'd only do this if the object is somehow capable of knowing when it's no longer needed, which usually would be (as Mike says) because it's part of some framework that doesn't manage object lifetime explicitly, but does tell its components that they've been detached/deregistered/whatever[*].
If I remember correctly, James Kanze is your man for this. I may have misremembered, but I think he occasionally mentions that in his designs delete this isn't just used but is common. Such designs avoid shared ownership and external lifecycle management, in favour of networks of entity objects managing their own lifecycles. And where necessary, deregistering themselves from anything that knows about them prior to destroying themselves. So if you have several "tools" in a "toolbelt" then you wouldn't construe that as the toolbelt "owning" references to each of the tools, you think of the tools putting themselves in and out of the belt.
[*] Otherwise you'd have your factory return a unique_ptr or auto_ptr to encourage callers to stuff the object straight into the memory management type of their choice, or you'd return a raw pointer but provide the same encouragement via documentation. All the stuff you're used to seeing.
A good rule of thumb is not to use delete this.
Simply put, the thing that uses new should be responsible enough to use the delete when done with the object. This also avoids the problems with is on the stack/heap.
Once upon a time i was writing some plugin code. I believe i mixed build (debug for plugin, release for main code or maybe the other way around) because one part should be fast. Or maybe another situation happened. Such main is already released built on gcc and plugin is being debugged/tested on VC. When the main code deleted something from the plugin or plugin deleted something a memory issue would occur. It was because they both used different memory pools or malloc implementations. So i had a private dtor and a virtual function called deleteThis().
-edit- Now i may consider overloading the delete operator or using a smart pointer or simply just state never delete a function. It will depend and usually overloading new/delete should never be done unless you really know what your doing (dont do it). I decide to use deleteThis() because i found it easier then the C like way of thing_alloc and thing_free as deleteThis() felt like the more OOP way of doing it

Get (pointer to) calling object

I have an object -a scheduler class-. This scheduler class is given member function pointers, times and the pointer to the object which created the scheduler.
This means I could do something as much as: (pObject->*h.function)(*h.param); Where pObject is the pointer to the original object, h a class which contains the function + void pointer parameter so I can pass arguments to the original function.
When I like to initialize this object I have the explicit Scheduler(pObjType o); constructor (where pObjType is a template parameter).
When I create an object which should have this alarm I type:
struct A {
typedef void (A::*A_FN2)(void*);
typedef Scheduler<A*,A_FN2> AlarmType;
A(int _x) : alarm(NULL)
{
alarm.SetObject(this);
}
AlarmType alarm
However this alarm-type puts quite a big limitation on the object: if I forget to add a copy-constructor (to A) the class would get undefined behaviour. The scheduler would keep pointing to the original object, and that original object might go out of scope, or even worse, might not.
Is there a method that when I copy my alarm (by default, so in the scheduler's copy-constructor) I can get the calling object (and pointer to that?)?
Or if that isn't possible, is it possible to throw a (compile) error if I forget to implement a copy-constructor for my structure? - And try to copy this structure somewhere?
As I see it, you have an opportunity to improve your design here, that may help you get rid of your worry.
It is usually a bad idea to pass
around member function pointers. It
is better to make your structs
inherit from an abstract base class,
making the functions you want to
customize abstract virtual.
If you don't need copying, it is best
to disallow it in the base class.
Either by making the copy constructor and operator undefined and private,
or by inheriting boost::NonCopyable.
If you want any kind of automatic copy construction semantics, then you're going to need to go to the CRTP- no other pattern provides for a pointer to the owning object.
The other thing is that you should really use a boost::/std::function<>, they're far more generic and you're going to need that if you want to be able to use Lua functions.
The simplest way to prevent the specific issue you're asking about is to make Scheduler noncopyable (e.g. with boost::noncopyable). This means that any client class incorporating a value member of type Scheduler will fail to be copyable. The hope is that this provides a hint for the programmer to check the docs and figure out the copy semantics of Scheduler (i.e. construct a new Scheduler for every new A), but it's possible for someone to get this wrong if they work around the problem by just holding the Scheduler by pointer. Aliasing the pointer gives exactly the same problem as default-copy-constructing the Scheduler instance that holds a pointer.
Any time you have raw pointers you have to have a policy on object lifetime. You want to ensure that the lifetime of any class A is at least as long as the corresponding instance of Scheduler, and as I see it there are three ways to ensure this:
Use composition - not possible in this case because A contains a Scheduler, so Scheduler can't contain an A
Use inheritance, e.g. in the form of the Curiously Recurring Template Pattern (CRTP)
Have a global policy on enforcing lifetimes of A instances, e.g. requiring that they are always held by smart pointer, or that cleaning them up is the responsibility of some class that also knows to clean up the Schedulers that depend on them
The CRTP could work like this:
#include <iostream>
using namespace std;
template<typename T>
struct Scheduler {
typedef void (T::* MemFuncPtr)(void);
Scheduler(MemFuncPtr action) :
action(action)
{
}
private:
void doAction()
{
this->*action();
}
MemFuncPtr action;
};
struct Alarm : private Scheduler<Alarm> {
Alarm() : Scheduler<Alarm>(&Alarm::doStuff)
{
}
void doStuff()
{
cout << "Doing stuff" << endl;
}
};
Note that private inheritance ensures that clients of the Alarm class can't treat it as a raw Scheduler.