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

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

    A few things that usually trip people up:

    std::cout << a << a++ << --a;
    i = ++i;
    

    The above lines are both undefined.

    void foo(bar* b1, bar* b2);
    
    int main() {
      foo(shared_ptr(new bar()), shared_ptr(new bar()));
    }
    

    The above may leak memory.

    int* arr = new int[10];
    arr + 11;
    

    This results in undefined behavior.

    As for idioms, my favorite is RAII. Allocate objects on the stack, which guarantees that the destructor is called when the object goes out of scope, preventing resource leaks.

提交回复
热议问题