Recently I have seen code similar to this:
foo.cpp:
#include <memory>
struct Foo { /* some code */ };
std::unique_ptr<Foo> makeFoo() { return std::make_unique<Foo>(); }
// No other instantiation of Foo whatsoever in this file
bar.cpp:
extern std::unique_ptr<Foo> makeFoo();
void someFunc() {
auto myFoo = makeFoo();
// ...
}
As you can see, Foo
as such would not require a factory function like makeFoo()
, but because no header declaration is provided (and there is no such thing as extern class Foo;
), it is still needed to instantiate Foo
in other translation units (TUs).
This leads me to the following (related) questions:
- Why would one want to write such code? Is there any benefit in this particular case over just splitting
Foo
into header/source or can I consider this an antipattern? The intention is to instantiateFoo
in other TUs anyway. - When writing new code (i.e. no need to access other people's code with
extern
), why would one want to useextern
anyway? In my view, unless technical reasons apply,extern
leads to convoluted and less maintainable code. In particular I'd be interested in any advantages over header files.
Note that I am referring to linkage specifiers here, not to other usages of the keyword such as extern template
).