0

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 instantiate Foo 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 use extern 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).

andreee
  • 4,459
  • 22
  • 42
  • 1
    For function declarations? No. For variable declarations? It's mandatory or it's a definition. โ€“ Some programmer dude Sep 16 '21 at 06:41
  • I am voting to reopen. The linked question does _not_ answer my question. I am not asking about the usage of `extern` in a header file (I'm aware that functions have external linkage by default), but asking about possible benefits of `extern` in the shown example. โ€“ andreee Sep 16 '21 at 08:23
  • This question really has the scent of any answer being an opinion. My 2ยข opinion is that writing this, rather than using a header file is intending on this being the *only* use of that function outside of it's translation unit, and not polluting the header file with this, as the header file is the 'agreed ' API. โ€“ Anya Shenanigans Sep 18 '21 at 15:07

0 Answers0