When using unique_ptr, it is easy to forget to initialize the pointer, which may lead to a crash at runtime.
Why is unique_ptr defined with a default constructor leaving it pointing to nullptr? If it had always required a constructor parameter, the programmer would be forced to put it in the initializer list. Okay, if the default constructor is useful, wouldn't it also be useful with some kind of valid_unique_ptr that requires a constructor argument?
Should I subclass unique_ptr to force initialization, or maybe wrapping would be the way to go?
I'm a bit surprised I can't find this suggested or done anywhere...
Example:
#include "XTimerFactory.h"
struct MyClass {
MyClass(XTimerFactory& timerFactory)
: m_timer(timerFactory.createTimer()) // <- Crucial, or program will crash later
{ }
void start() { m_timer->start(100); }
private:
std::unique_ptr<XTimer> m_timer;
}