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

前端 未结 16 2134
刺人心
刺人心 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:15

    One seldom used, but handy C++ idiom is the use of the ?: operator during the constructor chain.

    class Sample
    {  
        const char * ptr;
        const bool  freeable;
    
        Sample(const char * optional):
            ptr( optional ? optional : new char [32]),
            freeable( optional ? false : true ) {}
        ~Sample( )  { if (freeable) delete[] ptr; }
    }  
    

    C++ doesn't allow const values to be changed inside the body of the constructor, so this avoids const-casts.

提交回复
热议问题