Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most crucial elements in a light-weight C++ coding standard [closed]

Prefer RAII.

STL's auto (and shared in boost & C++0x) pointers may help.


Use const identifiers by default. They provide guarantees for the reader/maintainer, and are way easier to build in than to insert afterwards.

Both member variables and methods would be declared const, as well as function arguments. const member variables enforce proper use of the initializer list.

A side-effect of this rule: avoid methods with side-effects.

------ EDIT

const member variables seemed like a good idea; this is not always the case: they effectively make any object immutable. This becomes problematic for e.g. sorting a vector.

struct A {
    const int i;
};

bool operator<(const A& lhs, const A& rhs) {
    return lhs.i < rhs.i;
}

int main() {
    std::vector<A> as;
    as.emplace_back(A{1});
    std::sort(begin(as), end(as));
}

error message:

... note: copy assignment operator of 'A' is implicitly deleted because
field 'i' is of const-qualified type 'const int'
...
in instantiation of function template specialization 'std::sort<...>'
requested here

    std::sort(begin(as), end(as));


Use C++ casts instead of C casts

use:

  • static_cast
  • const_cast
  • reinterpret_cast
  • dynamic_cast

but never C-style casts.

How it clearly facilitates safer code, which minimizes the risk of enigmatic bugs, which increases maintainability, etc.

Each cast has limited powers. E.g., if you want to remove a const (for whatever reason), const_cast won't change the type at the same time (which could be a bug difficult to find).

Also, this enables a reviewer to search for them and then, the coder to justify them if needed.


Use references instead of pointers where possible. This prevents constant defensive NULL checks.