Const, Pointers and References

Summary

In this post, I will introduce const, * and & and their combinations. I also have similar posts discussed auto and &.

Conclusion

As usual, I present the golden rule first: “read from right to left”. In other words, the const-on-the-right style always puts the const on the right of what it constifies”.

  1. When you want a pointer which can not change the object, use CNN const * cnn_ptr = new CNN(model);;
  2. When you want a pointer which can not point to other objects, use CNN * const cnn_ptr = new CNN(model);;
  3. When you want a pointer which can not change the object and can not point to other objects, use CNN const * const cnn_ptr = new CNN(model);
  4. When you want a reference which can not change the object, use CNN const & cnn_ref = model;;

Details

1. const CNN * or CNN const *

Read it from right to left. CNN const * cnn_ptr means “cnn_ptr points to an CNN instance that is const”: the CNN object can’t be changed via cnn_ptr. CNN const * cnn_ptr is equivalent to CNN const * cnn_ptr. However, I prefer the former, which is the const-on-the-right style.

The const-on-the-right is a consistent style: it always puts the const on the right of what it constifies. In which, a local variable that is const is defined with the const on the right: int const a = 42;. Similarly a static variable that is const is defined as static double const x = 3.14;. Basically every const ends up on the right of the thing it constifies.

2. CNN * const cnn_ptr

Read it from right to left. CNN * const cnn_ptr means “cnn_ptr is a const pointer to an CNN instance that is non-const”: you can’t change the pointer cnn_ptr itself, but you can change the CNN object via the cnn_ptr. const constifies *, which makes us happy.

3. CNN const * const cnn_ptr

Read it from right to left. It means “cnn_ptr is a const pointer to an CNN instance that is const”: you can’t change the pointer cnn_ptr itself, nor can you change the CNN instance via cnn_ptr.

4. CNN const & cnn_ref

Read it from right to left. “cnn_ref is a reference to a const CNN”. CNN const & cnn_ref is equivalent to const CNN & cnn_ref.

5. CNN & const cnn_ref ???

“cnn_ref is a const reference to a CNN”? It makes no sense. Once combined, cnn_ref can not combine other instances. That is, CNN& const cnn_ref is always equivalent to CNN& cnn_ref.

Reference

isocpp.org

Leave a Reply

Your email address will not be published. Required fields are marked *