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

前端 未结 16 1991
刺人心
刺人心 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条回答
  •  萌比男神i
    2021-01-29 20:19

    Since we're all ignoring the OP and instead posting our favourite cool tricks...

    Use boost (or tr1) shared_ptr to maintain a class invariant at runtime (kind of obvious, but I haven't seen anyone else do it):

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    using namespace boost;
    
    class Foo
    {
    public:
        Foo() : even(0)
        {
            // Check on start up...
            Invariant();
        }
    
        void BrokenFunc()
        {
            // ...and on exit from public non-const member functions.
            // Any more is wasteful.
            shared_ptr checker(this, mem_fun(&Foo::Invariant));
    
            even += 1;
            throw runtime_error("didn't expect this!");
            even += 1;
        }
    
    private:
        void Invariant() { assert(even % 2 == 0); }
        int even;
    };
    

提交回复
热议问题