3

I am needing to upgrade some legacy code to no longer rely on global variables. A pattern I am finding is something like:

int foo() { 
  int i = some_number_from_hyperspace(); // Thread-safety problems
  return i * 42; 
}

Whereas the better approach would be

int foo(int i) { 
  return i * 42; 
}

and to deprecate the some_number_from_hyperspace function. The way I would prefer to deprecate, while keeping things maintainable, is to use the following idiom:

[[deprecated]] int some_number_from_hyperspace();

int foo(int i = some_number_from_hyperspace()) {
  return i * 42;
}
foo(); // Deprecation warning
foo(2); // No warning

This pattern appears to work for MSVC 19.22, however, neither GCC 9.2 or Clang 8 appear to support it. Feel free to experiment:

https://godbolt.org/z/LWCghE

As much as I like the MSVC behavior, the code must be supported by GCC and Clang. I'm guessing that the timing of when attributes are applied depends on the implementation. Am I right? Any other suggestions about how to approach this problem?

L. F.
  • 19,445
  • 8
  • 48
  • 82
KyleKnoepfel
  • 1,426
  • 8
  • 24
  • 1
    You may be experiencing a standard selection issue or an old compiler issue: https://stackoverflow.com/a/39956021. When I try clang++ v7 it likes `[[deprecated]]` with `--std=c++14`, and g++ v8.2 will accept it unless you specify a pretty early `--std`. – dmckee --- ex-moderator kitten Aug 22 '19 at 20:27
  • @dmckee clang 8 and gcc 9.2 [both warn on `--std=c++17`](https://godbolt.org/z/ice7wA) – Artyer Aug 22 '19 at 20:31
  • @Artyer Thanks. I confirm that, and the required standard is c++17. – KyleKnoepfel Aug 22 '19 at 20:32
  • `[[deprecated]]` doesn't exist in C++11. Please update the tag. – L. F. Aug 22 '19 at 20:42
  • @Artyer: but they warn on default argument even if not called. whereas msvc only warns when it is actually called. [Demo](https://godbolt.org/z/wY-xAx) – Jarod42 Aug 22 '19 at 20:47
  • Unrelated: If it's not too much work you could also put the deprecated stuff in a namespace of its own to make it pop out when debugging etc: [Example](https://godbolt.org/z/Z2z5t2) – Ted Lyngmo Aug 22 '19 at 20:54
  • The link you provide seems to show the same warnings from all three compilers (although GCC emits them twice for some reason). – Davis Herring Aug 23 '19 at 04:32

0 Answers0