C++14 best practices
I just watched Herb Sutter's CppCon 14 address and felt a need to make a note to myself of a couple of things:
- Call functions with raw references or pointers to entities that live at least as long as your scope.
- Don't overuse pass-by-value even for parameters you're going to copy unconditionally — a combination of copy and move assignment perform better in important cases because an unconditionally copied parameter cannot take advantage of existing capacity at the final destination.
Prefer
to thisvoid set_name(std::string const& name); void set_name(std::string&& name);
void set_name(std::string name);
- Assuming you have a class hierarchy C0 <| C1 <| … and corresponding factory template functions.
If you'd like to keep an arbitrary instance around for the duration of a scope while erasing its type, you might think this requires heap allocation.
But it's not true: a reference to the base type will do just fine!
The result of the factory is stored in a temporary and its lifetime is determined by the lifetime of the reference. The idea came from Andrei Alexandrescu's ScopeGuard.{ C0 const& c0 = cFactory(…); /* … */ }
Comments
Post a Comment