casyup.me@outlook.com

0%

other/auto+const+pointer

auto+const+pointer

在项目中遇到了需要使用auto的场景,那是一个复杂类型的指针。使用时出了一些疑问,所以有了这篇笔记。

I’ve got a problem when I need to use the ‘auto’ keyword in a project. This’s why I wrote this note.

参考以下代码:

think flowing codes

1
2
3
int i = 1;
int *p = &i;
auto p2 = p;

此时我想要 p2 安全一些,我不想改变 i 的值,那么或许可以这样做:

if I want p2 to be safer and don’t want to change the value of ‘i’, maybe I can do this:

1
auto const p2 = p; // or const auto p2 = p; ?

这里 consnt 在 auto 位置不影响其语义,p2 依旧可以改变 i 的值。(ps:双 const 会报错)

The position of ‘const’ at ‘auto’ doesn’t affect anything. The value of ‘i’ still can be changed by ‘p2’. (PS: double-const will get an error)

我想要的是一个双 const 的指针,如何实现呢?

I want a double-const pointer, how can get it?

1
auto const* const p2 = p;

Emmm, 好像并不是很有意义写这篇笔记

it seems doesn’t make sense to write this note…