C++ Don'ts

Undefine Behaviour

return for [[noreturn]]

sourcearrow-up-right

[[noreturn]] constexpr int DontDoThis() { return 42;}
constexpr auto Execute() { return DontDoThis();}
std::cout << "Execute " << Execute() << std::endl; // segmentation fault

Iterator Invalidation

    std::vector<int> vec = {1, 2, 3, 4, 5};
    {
      auto it = vec.begin();
      
      // bug: push_back may cause reallocation, invalidating all iterators
      vec.push_back(4);
      vec.push_back(5);
      std::cout << *it; // undefined behavior
    }
    {
      for (auto it = vec.begin(); it != vec.end(); ) {
          if (*it == 3) {
              // vec.erase(it); // this would cause iterator becomes invalid
              it = vec.erase(it); // erase returns next valid iterator
          } else {
              ++it;
          }
      }
    }
  • Remove-erase idiom

Bad Practice

Disable Return Value Optimization (RVO or Named RVO)

source: Item 25: Effective Modern C++arrow-up-right

  • Do this instead

Calling Virtual Functions during Construction or Destruction

source: Item 9: Effective C++arrow-up-right

  • During base class construction, virtual functions never go down into derived classes.

Last updated