4.6.0
Freundlich's C++ toolkit
|
When parameters are passed to functions, especially constructors, use one of the following cases to indicate ownership:
T &&
for types that are expensive to copy. This forces callers to pass an rvalue reference and make it explicit if they need to provide a copy, e.g. T
. T const &
. fcppt::unique_ptr<T> &&
. fcppt::reference<T>
. In this case, it makes it clear to the caller that he has to keep the object alive. fcppt::shared_ptr<T>
. This case should be considered last. nullptr
. Following are various points on how to design the interface of a class:
Avoid default constructors! Default constructors are usually a sign of bad design, e.g. some code wants to assign to an object but does not need its value. Instead of using a default constructor, simply pass the desired values, e.g. int i{0};
instead of int i{};
. If you do not have a value for the object yet, do not create it in the first place!
There are several types which replace standard types with the explicit intend not to be default-constructible, e.g. fcppt::function, fcppt::unique_ptr, fcppt::shared_ptr and fcppt::variant::object.
= default
can be used. Following are various points about functions:
void f(std::string const &name, std::string const &email);
use void f(int x, int y);
, use void f(fcppt::math::vector::static_<int,2>);
. Avoid explicit loops if possible. There are many cases in which an algorithm can be used instead. For example, instead of
you can use fcppt::algorithm::fold
Algorithms can only be used with ranges, not with iterators. In case you need to encapsulate iterators, use fcppt::iterator::range. There are also special ranges like fcppt::int_range or fcppt::enum_::range. Some algorithms also accept an fcppt::mpl::list::object as a range in case you need to iterate over types.
Initialize all objects and make them const if possible, especially do not use default constructors.
Provide functions for cases in which initialization can not be expressed directly. Consider a function that initializes an array of arbitrary size:
Say you have a function T from_index(std::size_t)
that creates an array element given an index. You can then initialize the array using
In case you really need uninitialized objects, create a constructor that takes fcppt::no_init.