1

Here's a scenario:

suppose you have #include <unordered_map> in the header and you don't declare it anywhere in the implementation file

but you use it, maybe

mp[whatever] = some;

should you re-include the <unordered_map> header? what is best practice?

in general, what's the best practice w.r.t relying on transitive includes like this, assuming that those things you are relying on are perhaps part of the method type signatures or member variables?

to be more explicit:

std::unordered_map<>

might occur in the header

but no way does the type appear in the implementation. An object of that type is only used.

user129393192
  • 255
  • 2
  • 7

1 Answers1

5

When

  • a header file A.h requires an include for <unordered_map>, and

  • the related cpp file A.cpp (which includes A.h) contains some code dealing with objects of type unordered_map (regardless whether that type is written explicitly in the cpp or not)

there is no clear consensus in the C++ community whether A.cpp should include <unordered_map> as well or not.

Source: David Kieras,, C++ Header File Guidelines (2015), see page 3, Guideline #12. That paper also explains the two possible point of views, either

  • the two includes are redundant, or

  • readability should be favored over redundancy in this case

IMHO both POV can be justified. I would recommend to pick one of the two conventions and stick to it throughout your code base.

Doc Brown
  • 218,378