What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience?

前端 未结 16 1808
刺人心
刺人心 2021-01-29 19:48

What are some C++ related idioms, misconceptions, and gotchas that you\'ve learnt from experience?

An example:

class A
{
  public: 
  char s[1024];
  cha         


        
相关标签:
16条回答
  • 2021-01-29 20:20

    Never waste time on trying to implement the copy operations on classes when we don't know if it will be required later. Many objects we handle are just entities, and copying them hardly make any sense. Make them non-copyable, and implement the copy/duplication later if the need really arises.

    0 讨论(0)
  • 2021-01-29 20:23

    You can often hide way more stuff in source files than you think. Don't make everything private if you don't have to - it's often better to leave it in an anonymous namespace in the source file. It actually makes things easier to process, I find, because then you aren't revealing implementation details, yet get inspired to make lots of tiny functions rather than monolithic ones.

    0 讨论(0)
  • 2021-01-29 20:26

    Since I learned about RAII (one of the worst acronyms ever) and smart pointer, memory and resource leaks have almost completely disappeared.

    0 讨论(0)
  • 2021-01-29 20:27

    Sometimes, headers are polluted with not behaving macro names like

    #define max(a, b) (a > b ? a : b)
    

    Which will render code invalid that uses a max function or function object called that way. An infamous example is windows.h which does exactly that. One way around it is putting parentheses around the call, which stops it from using the macro and makes it use the real max function:

    void myfunction() {
        ....
        (max)(c, d);
    }
    

    Now, the max is in parentheses and it is not counted as a call to the macro anymore!

    0 讨论(0)
提交回复
热议问题