iammilind
iammilind

Reputation: 70030

Is it advisable to declare pointer to heap memory as `const` ALWAYS?

T *p = new T();

For the pointer on heap, there can be disastrous operations such as,

p++;  // (1) scope missed
p = new T(); // (2) re-assignment

Which would result in memory leaks or crashes due to wrong delete. Apart from using smart pointers, is it advisable always to make heap pointer a const;

T* const p = new T();  // now "p" is not modifiable

This question is in regards of maintaining good programming practice and coding style.

Upvotes: 10

Views: 522

Answers (4)

Bo Persson
Bo Persson

Reputation: 92311

I believe it is unusual to use a pointer if it is not going to change. Perhaps because I hardly ever use new in normal code, but rely on container classes.

Otherwise it is generally a good idea to preserve const-correctness by making things const whenever possible.

Upvotes: 1

Andrei
Andrei

Reputation: 5005

There is one major potential problem I see with this:

after delete you should set the pointer to NULL to (help) prevent it being used in other parts of the code.

Const will not allow you to do this.

Upvotes: 2

user2100815
user2100815

Reputation:

Well, about the only time I use raw heap pointers is if writing my own data structures. and if you used a const pointer for them, your data structure immediately becomes unassignable. which may or may not be what you want.

Upvotes: 7

John Zwinck
John Zwinck

Reputation: 249394

I hesitate to say always, but what you propose seems reasonable for many/most cases. Const correctness is something most C++ folks pay a fair bit of attention to in function parameters, but not so much in local (or even member) variables. We might be better off to do so.

Upvotes: 2

Related Questions