Non-performance-Related C++ Language Features, Continued
Learn about more features and drawbacks of the C++ language.
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++
The destruction of objects is deterministic in C++. That means that we (can) know exactly when an object is being destroyed. This is not the case for garbage-collected languages like Java where the garbage collector decides when an unreferenced object is being finalized.
Get hands-on with 1400+ tech skills courses.