Search⌘ K
AI Features

Non-performance-Related C++ Language Features, Continued

Learn about key C++ language features not directly tied to performance such as strict object ownership, deterministic destruction, and using references to avoid null objects. Understand how these features improve code safety and predictability, and discover some drawbacks of C++ like long compile times and limited standard libraries. This lesson builds foundational knowledge vital for writing robust C++ code in advanced projects.

Object ownership

Except in very rare situations, a C++ programmer should leave the memory handling to containers and smart pointers and never have to rely on manual memory handling.

To put it clearly, the garbage collection model in Java could almost be emulated in C++ by using std::shared_ptr for every object. Note that garbage-collecting languages don’t use the same algorithm for allocation tracking as std::shared_ptr. The std::shared_ptr is a smart pointer based on a reference-counting algorithm that will leak memory if objects have cyclic dependencies. Garbage-collecting languages have more sophisticated methods that can handle and free cyclic-dependent objects.

However, rather than relying on a garbage collector, forcing a strict ownership delicately avoids subtle bugs that may result from sharing objects by default, as in the case of Java.

If a programmer minimizes shared ownership in C++, the resulting code is easier to use and harder to abuse, as it can force the user of the class to use it as it is intended.

Deterministic destruction in C++

...