Pass function enumeration - by value or by reference?

Correct mine if I am wrong, but the reason you pass integers and other basic data types by value is because the memory they occupy is too small, so the waste makes up a pointer variable of this data type (which will probably be at least the same size as the data type).

This is why I always pass in intother base types by value for functions, and other (larger) data types are passed by const references or pointers to const. I got it right?

Now I have seen many APIs that pass types enumas const references, for example:

enum FileOptions { ReadOnly, ReadWrite, WriteOnly };
void processFile(const FileOptions &options);

As far as I know, enumerations are usually interpreted by the compiler as prime integers, so why are they passed by reference? This is done for an abstract data type from the developer, so he won’t think about FileOptionshow an integer? (although it is).

+4
source share
4 answers

The only advantage that I see is that if you later decide to create a class with advanced functionality, you can still pass it efficiently without changing the code anywhere.

In any case, any worthy optimizer does not care about the link, if it is a link to const for the base type, and creates the same code in both cases.

, - , , ( , const), , , . , .

+1

, "const int".

, - , .

, .

0

++ enum, . , const .

, , , , const. , enum . , ..

enum , .

0

: , , . const amp;, - , , FileOptions, , const &, .

, . , , (, , , ), , , .

& , , , , , const & . const & , . int, , , 10 int, .

Another use is for const & instead of a value for objects that cannot be easily copied. For example, a mutex cannot be easily copied. Or, an object that provides exclusive access to a file may, by definition, not be copied meaningfully.

-1
source

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


All Articles