Nissim Levy
Nissim Levy

Reputation: 165

member pointer to const

I am trying to implement the rule of five using the swap idiom.

however, i have internal member fields that are const.

I tried at first to make const_cast, but as I see it probably impossible in this case.

I got into conclusion that the best way will be to turn the member field into ptr to const.

I tried to do this via the initalization list, but cannot find the right syntax. the following doesn't compile:

HashMap<KEY, VALUE>::HashMap(double threshold)
: *_thresholdPtr(threshold)

...

const double * _thresholdPtr;

I will be grateful to your help, first if ptrs to const are the best way in this case, and how to do it if yes.

thanks!

EDIT: I know that const double* is not like double * const. but what I'm trying to do is to recieve a double number, and attach it as a const double to a pointer which is not const (in order to be able to use the swap)

Upvotes: 1

Views: 99

Answers (1)

Ryan Mueller
Ryan Mueller

Reputation: 84

The order where your const declaration happens in relation to the data type matters when declaring pointers. const double *_thresholdPtr; creates a double that can be pointed to, but itself cannot be changed. double *const _thresholdPtr; creates a constant pointer to an existing double.

I'm not sure if it will help, but I ran into a similar issue with some code. This post helped me understand the difference.

EDIT: As comment below, the difference is where pointer is declared.

Upvotes: 0

Related Questions