C++ Don'ts
Undefine Behaviour
return for [[noreturn]]
[[noreturn]] constexpr int DontDoThis() { return 42;}
constexpr auto Execute() { return DontDoThis();}
std::cout << "Execute " << Execute() << std::endl; // segmentation faultIterator 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;
}
}
}Bad Practice
Disable Return Value Optimization (RVO or Named RVO)
Calling Virtual Functions during Construction or Destruction
Last updated