简体   繁体   English

指向const的成员指针

[英]member pointer to const

I am trying to implement the rule of five using the swap idiom. 我正在尝试使用交换惯用法来实现5条规则。

however, i have internal member fields that are const. 但是,我有内部成员字段是const。

I tried at first to make const_cast, but as I see it probably impossible in this case. 我最初尝试制作const_cast,但据我所知在这种情况下可能是不可能的。

I got into conclusion that the best way will be to turn the member field into ptr to const. 我得出的结论是,最好的方法是将成员字段转换为ptr到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. 如果您将ptrs指向const是这种情况下的最佳方法,那么我将不胜感激,如果可以,那么该如何做。

thanks! 谢谢!

EDIT: I know that const double* is not like double * const. 编辑:我知道const double *不像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) 但是我想做的是接收一个双精度数,并将其作为const double附加到不是const的指针上(以便能够使用交换)

The order where your const declaration happens in relation to the data type matters when declaring pointers. 在声明指针时, const声明相对于数据类型发生的顺序很重要。 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 . 创建一个指向现有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. 编辑:作为下面的注释,不同之处在于指针的声明位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM