Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it common to declare const pointers in C++?

C++ style guides strongly advise that one should declare objects as const if we don't intend to modify them. It follows that when we declare a pointer to an object/variable that isn't going to be reassigned we should declare it const:

T* const pObject = new T();

It just seems that C++ developers usually don't follow this rule in case of pointers, do they?

like image 481
embedc Avatar asked Dec 02 '22 09:12

embedc


1 Answers

A pointer is an object.

If you wish to prevent modification of the value held by the pointer, i.e. to make it hold only a single address within its lifetime, then yes make it const. The same considerations that apply for any other object type also apply here.

I suspect the reason you may not see it much is that the declarator syntax in C++ kinda makes this uncomfortable to type. Not to mention that whether or not the pointee is const is usually far more important.

like image 200
StoryTeller - Unslander Monica Avatar answered Jan 28 '23 15:01

StoryTeller - Unslander Monica