C++: Is it better to pass an enum as a value or as a const reference?

后端 未结 5 1001
暗喜
暗喜 2020-12-30 21:41

There are sort of two related questions here:

A) How is enum implemented? For example, if I have the code:

enum myType
{ 
   TYPE_1,
   TYPE_2
};
         


        
5条回答
  •  感情败类
    2020-12-30 22:16

    Speed wise it almost certainly doesn't matter - any decent C++ compiler is just going to pass a single int.

    The important point is readability - which will make your code more obvious to the reader?

    If it's obvious that these enums are really just ints then I would pass them by value, as if they were ints. Using the const ref might cause a programmer to think twice (never a good idea!)

    However - if you are later going to replace them with a class then keeping the API the same and enforcing the const-ness might make sense.

提交回复
热议问题