4

There are some predefined preprocessor macros (specified in C and C++ standard) like __line__ and __file__ which are replaced by line number and file name during preprocessing respectively. In C++20, a new class std::source_location is introduced which does more or less the same thing.

So, my questions are...

  • What are the differences between them?
  • What are their advantages and disadvantages?
  • Which one I should use for which reason?
Akib Azmain
  • 1,086
  • 4
  • 27
  • As stated on [cpp reference](https://en.cppreference.com/w/cpp/utility/source_location), "It is intended that source_location has a small size and can be copied efficiently. – Tom Sep 01 '20 at 07:41
  • One difference is that with `std::source_location` objects you no longer need "ugly" macros for many things, you can use simple functions (as shown in e.g. [this example](https://en.cppreference.com/w/cpp/utility/source_location#Example)). – Some programmer dude Sep 01 '20 at 07:44

1 Answers1

4

Preprocessor macros live outside the type system. Preprocessor macro substitution happens outside the rest of the language. See this answer and this answer for a comprehensive discussion of the disadvantages of using the preprocessor.

std::source_location on the other hand behaves like any other C++ struct. It has plain value fields that are typed and behave like any other values in the language.

Besides that, functionality-wise the two mechanisms are equivalent. There is nothing that the one can achieve that cannot be done by the other (apart from the column field in source_location, which has no equivalent in the preprocessor). It's just that the new approach achieves its goals more nicely.

Akib Azmain
  • 1,086
  • 4
  • 27
ComicSansMS
  • 46,689
  • 13
  • 143
  • 152