Aussie AI

C++ Class Slugs

  • Book Excerpt from "Generative AI in C++"
  • by David Spuler, Ph.D.

C++ Class Slugs

The C++ class features are designed to add encapsulation and modularity, while retaining speed, but there's still plenty of ways that slugs can crawl into your classes. C++ class optimizations include:

  • Ensure small member functions are inline, especially those that do “get” and “set”.
  • Add inline to other friend or non-class functions (esp. if small or commonly used).
  • Pass objects to functions using “const&” (pass-by-reference), rather than pass-by-value.
  • Watch out for temporary objects. These can occur in simple assignments or function call expressions or in weird ways like accidentally making your overloaded assignment operator have the wrong type.
  • Use reference variables instead of copying objects into temporary variables.
  • Take care templating class objects (e.g. when using the std::vector class for a vector of your class objects). Lots of hidden calls to constructors and destructors may arise in resizing.
  • Use the initializer list in the constructor for initializing data members.
  • Use friend functions for faster accesses to internal object data.
  • Block accidental calls to the copy constructor or class assignment operator (i.e., if you aren't defining them, make a dummy version that is “private” with a “void” function body).
  • Avoid returning objects if you can. Return a reference if it's safe to do so.
  • Take care with “wrapper” classes like “smart pointers”, “smart integers” or “smart buffers”. Usually, they're safer but slower. How smart is that?

 

Next:

Up: Table of Contents

Buy: Generative AI in C++: Coding Transformers and LLMs

Generative AI in C++ The new AI programming book by Aussie AI co-founders:
  • AI coding in C++
  • Transformer engine speedups
  • LLM models
  • Phone and desktop AI
  • Code examples
  • Research citations

Get your copy from Amazon: Generative AI in C++