I have a C++ issue, it's not often I can pick fault, but this is one of them... For years, I've used the factory create pattern; or at least my take on that pattern.
Whereby I make the constructor private, or the whole class "Uncopyable/Uncreatable", and then I add a new static function which returns the class wrapped into a smart pointer.
By doing this, I get the advantage that no-one can use outdated "new" calls on it, and I drastically reduce the potential for third party memory leak creation/exploitation.
I can still do this with C++14, however, for a while now authors have recommended using "std::make_shared". Their points are valid, but they break my factory creation pattern. Which has much more to offer me than just using "make_shared" or whatever smart pointer creation template.
Lets take a look...
So, we have the class, but we're creating and deleting it in the old style, anyone forgetting to perform that delete will leak memory.
There, we can implement creating the class instance with a smart pointer...
A big change next however, we make the constructor private, to absolutely stop other programmers creating instances of our class with "new" and so totally negating anyone creating the class and potentially forgetting to delete it.
So we offer the programmer the static create function, which returns the shared pointer wrapped class... At least, that was the idea, as we can see, it utterly fails, because the std::make_shared template class is not a friend of our "foo" class.
Finally, we have to take a step back, to use the create, and hence enforcing our whole factory create pattern, we have to return this smart pointer wrapped instance after using "new". This is fine, it is the same as "std::make_shared", but feels like a retrograde step.
No comments:
Post a Comment