|
|
|
|
|
by gpderetta
3286 days ago
|
|
It is very different from having a static method returning an optional, which guarantees that you can access the optional (with at least an assert in debug mode) only if the object is actually successfully constructed. Using a separate initialize member function means that you may have objects in a zombie state laying around after a failed construction which lead to all kind of initialization order issues (you might get a pointer to the object, but is it initialized?). Also you need to remember to check the return type, which also need to be meaningful (does it return false on failure? or it returns 0 on success?). Two phase initialization is a known antipattern which is, unfortunately, widely used and lead to all kind of pains. Friends do not let friends use 2PI. edit: sorry, I misread your comment, you were referring to the static function returning a pointer, which as you note is almost the same as the optional version. It forces heap allocation though, which is bad. |
|
This pattern of using a static create method is explicitly designed to avoid 2PI and is very common, especially in codebases that disable exceptions.
Also note that I'm not personally advocating using it, just that it is commonly used to avoid 2PI.