What does the use of underscores in C ++ mean? It is about its individual use, and not as part of a variable, etc. In particular, an example:

template <typename T> class VDeleter { public: VDeleter() : VDeleter([](T _) {}) {} ........................................ 

Thank you in advance!

  • This is usually something like a placeholder. Just variable. In this case, the constructor parameter of type T. - free_ze
  • Have you checked, is it compiled? As far as I remember, a name in C ++ cannot consist only of underscores, and it cannot begin with a digit. - Cerbo pm
  • @Cerbo this would be a strange limitation, because _ , unlike digits, is not used in syntax. Anyway, int main(int _, char** __) { return 0; } int main(int _, char** __) { return 0; } calmly going g++ -Wall main.c clang also normal. - D-side
  • @Cerbo, compiled - Denmark

2 answers 2

There is a common practice, not only in C ++, to give the name _ those values ​​or variables that will not be accessed . Such "no matter what", what to give a meaningful name does not have (ahem) sense.

Somewhere is part of the semantics of the language, but in C ++ it is just a variable with a strange name. The optimizer can guess to work with this value, from where it is possible, as long as it does not affect the observed behavior . But this does not refer to the name, the compiler can do it with any other variable.

The fact that such a name is not a "special case" in the semantics of a language has several unpleasant consequences:

  • impossibility to declare several such in one scope (in one argument list, for example)
  • lack of compliance (technically it’s possible to access such a variable)

Why this argument should be there at all - in each case it should be considered separately, but there are cases.

A simple example right in the language: in C ++, to overload the post-increment ( i++ ), you need to overload the operator++(int) . But no int is passed to the operator. Why is he? To distinguish from preincrement ( ++i ), whose signature is operator++() .

This is the most "meaningless argument" and can be called _ . To emphasize its meaninglessness.

And in the case of C ++ (reminds Harry ), more often you can remove the name altogether , which is devoid of the above disadvantages.

  • one
    This meaningless argument can not be indicated at all and can not be called ... - Harry
  • @Harry yes, in C ++ you can. In C clang swears (but there is no operator overload at all, this is an unfair comparison). Now I will note. - D-side

Using an underscore as a variable name is allowed. In this example, the variable will be available in the body of the lambda function.

But I think this is not the best way to name entities.