Consider this class:
class Widget
{
Widget::Widget();
bool initialize();
}
A Widget
has the following characteristics:
initialize()
must be invoked to fully constructinitialize()
may failinitialize()
is expensive
Given that, I am encapsulating creation in factory function that always returns the same Widget
instance:
Widget* widget() {
static auto w = new Widget;
static auto initialized = false;
if (!initialized) {
if (!w->initialize()) {
return nullptr;
}
initialized = true;
}
return w;
}
What should the return type of widget()
be?
In particular, I'd like to somehow make it clear that the lifetime of the returned Widget
will outlast any caller, but without referencing the internal implementation.
- Return a raw pointer and add a comment that states "The returned pointer points to an object with static storage duration that will not be deleted before the end of the program". This is simple, but not self-documenting.
- Return a
std::shared_ptr<Widget>
. This is self-documenting, but I don't like that it will introduce completely unnecessary reference counting overhead. - Return a
std::unique_ptr<Widget>
with a custom deleter function that is a no-op. I think this has the same perceived problem as #2 if the caller converts it into ashared_ptr
.
Aucun commentaire:
Enregistrer un commentaire