Ben Chuanlong Du's Blog

And let it direct your passion with reason.

Common Mistakes in C++ Code and Ways to Debug

Debugging

  1. gdb is a excellent command tool for debugging C/C++ code.

Syntax Mistakes

  1. Missing "}". When this happens, you usually get lots of error message when you compile your code. And these error messages are often hard to understand and seems not related to your code.

  2. Missing template arguments. This …

Performance Tips for C++

Performance

  1. If there is some block of useless code, the compile is smart enough to ignore it and thus speed up the program.

  2. Use the option -O2 to generate optimized code when you are ready to publish your code.

  3. Define variables only when needed to avoid the overhead of creating …

Lambda Function in C++11

Lambda Function

Check [here[(https://github.com/dclong/cearn/tree/master/lambda) for illustrative examples for the following discussions.

  1. When capture variables, you can define new variables in the [] of a lambda expression. For example, if a lambda function need the sum of two double variable x and y, you …

Initializing Variables in C++

  1. {} is more powerful than () and thus is preferred over (). You should use always use {} except for a few cases where () is necessary. For example, if you want to create a vector of length 1000, you have to use
    vector<int>(1000);
    

instead of

    vector<int> {1000};

which create a vector …

Pointers in C++

Pointers

  1. No pointer, no polymorphism.

  2. C/C++ is notorious for raw pointers. While pointers can boost up the speed of programs, it invites a trillion chances for making mistakes. You should avoid using raw pointers, instead, consider using unique_ptr, shared_ptr and weak_ptr. They are almost as efficient as raw pointers …

Write Portable C++ Code

  1. Addresses on 64 and 32 OS are different, so you have to be careful when your program have to deal with address. For example, if you take the difference of two pointers/iterators, you should type std::ptrdiff_t (which is essentially a singed integer type). Using an arbitrary integer type …