Summary

Let’s recap and conclude what we have learned in this course.

We'll cover the following

Congratulations! Now, we know how to use const better than the average C++ developer. Don’t get complacent though. The real work starts now!

We have two tasks:

  • Apply the knowledge!
  • Share the knowledge!

The best way to share knowledge and teach people new practices is by leading by example. Using these new techniques consistently will make our colleagues curious, and we can share it with them. You can also go ahead and schedule a knowledge-sharing session where you explain what you learned and initiate a discussion.

Recap

  • Make local, global, and static variables const whenever possible to avoid accidental changes in their value and allow the compiler to optimize further.

  • Don’t make member variables const because it will prevent the compiler from generating special copy assignment functions and benefiting from move semantics.

  • Make member functions const whenever possible. It helps avoid accidentally changing the object’s state. It also provides some necessary guarantees to the caller.

  • Don’t return const values and be cautious with const pointers and references. Make sure that the object you point to or refer to will still exist when used. In short, avoid dangling pointers and references. But don’t hesitate to use const pointers and references in case you think it’s safe and you can spare some costly copies.

  • Take const parameters whenever you have no intentions to update them. In the case of values, this is mainly informational to the caller. For references and pointers, as in the case of an update, the caller has to deal with the consequences. Even if the compiler doesn’t enforce it, make sure that the function declaration matches the definition even in terms of constness for all the parameters and the return type.

Write code filling the virtues of constness, and you’ll live a calmer life as a developer!

Get hands-on with 1200+ tech skills courses.