Aug 4, 2014

[C++11] Guideline for lots of things XD

Reference: Beware of C++ - Nicolai Josuttus


Guideline for explicit constructor
  • The default constructor should never be explicit
    • If all arguments of an explicit constructor have default values, declare the default constructor separately
  • An initializer list constructor should never be explicit
    • otherwise, empty initializer list could match to default argument constructor:
      Constructor(int=0){};
  • Any other constructor should be explicit,
    if
    • parameters affect behavior instead of core content
  • Shouldn't the default constructor always be its own beast?
Guidelines for constexpr:

  • constexpr is not for optimization. The compilers can inline well already.
  • use constexpr when guaranteed static initialization is important
    e.g
    the construction of global atomics really cannot be deferred to run time.
  • use constexpr when you anticipate using the results to define array sizes or appear within template non-type arguments
  • "Making everything possible constexpr" is borderline insane. It leads to unnecessarily increased compile times, potential code bloat, and wishes to overload on constexpr so that we can select different algorithms for compile time and run time.
  • by all means "be generous", but use constexpr only when there is a potential need for guaranteed compile-time evaluation.
  • beneficial uses of constexpr on non-trivial computations aren't always obvious from past experience.

Guidelines for template parameters:

  • If knowing the object is always cheap to copy then pass by value.
  • If it might not be cheap to copy, making a choice:
    • if the expected type is likely to be an r-value and is moveable, then call by value so that the caller passes temporaries or uses move.
    • if it's not cheap to copy and not moveable, then still take by value and let the caller use std::ref()
    • otherwise use const l-value reference
      • think about whether and where to decay
  • If returning s.t in the argument, use a non-const l-value reference
  • If having to pass move semantics into other parts of the called function, declare as universal reference and forward<>
    • think about whether and where to decay

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.