What is the difference between writing a static const uint variable and an anonymous enum variable?

I looked at the asio ssl_client.cpp example and found this right at the top:

enum { max_length = 1024 }; 

I wonder if there is a difference between this and

 namespace { const int max_length = 1024; } 

or

 static const int max_length = 1024; 

Or maybe they are absolutely equal, but is it less?

+5
source share
2 answers

They are equivalent if you use it for a value, not a reference.

Idiom enum { constantname = initializer }; was very popular in header files, so you can use it in a class declaration without any problems:

 struct X { enum { id = 1 }; }; 

Since with a static member const you will need an initializer outside the class, and it cannot be in the header file.

Update

Cool kids do it these days:

 struct X { static constexpr int id = 1; }; 

Or they go with Scott Meyer No. 1 and write:

 struct X { static const int id = 1; }; // later, in a cpp-file near you: const int X::id; int main() { int const* v = &X::id; // can use address! } 

ΒΉ see Immediate integral static constants and constexpr of participants, No. 30

+3
source

Of course, it's worth mentioning that inside the class, declaring an enum value will not consume storage, while various const[expr] int flavors will ultimately take 4/8 / how many bytes.

Thus, if someone needs a structure containing only other members that occupy a certain number of bytes (for example, a POD that is converted to a byte structure from another system), specifying constants as enums seems to be the only way to do this.

Perhaps a rare but very good reason for this.

0
source

Source: https://habr.com/ru/post/1235707/


All Articles