In this dummy example below, I would like to create a Singleton where I can save the get_instance call which is costly on embedded microcontrollers.
#include <stdio.h>
template<class T>
class CamelBase {
public:
static T& get_instance() {
static T instance;
return instance;
}
protected:
CamelBase() {}
CamelBase(T const&) = delete;
void operator=(T const&) = delete;
};
class Camel: public CamelBase<Camel> {
public:
int answer() {
return 42;
}
};
int main(void)
{
printf("%d\n", Camel::get_instance().answer());
return Camel::get_instance().answer();
}
We can see here https://godbolt.org/g/1ugPxx that each call to answer
calls the get_instance
, which is weird because the compiler inlined answer
anyway.
main:
push {r4, lr}
bl CamelBase<Camel>::get_instance()
mov r1, #42
ldr r0, .L15
bl printf
bl CamelBase<Camel>::get_instance()
pop {r4, lr}
mov r0, #42
bx lr
Is there another way to write that kind of Singleton for peripherals such as I2C or SPI?
Is it better to use a static class? A reference pointer?