Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

T240516 Top-level const and Low-level const #11968

Open
guevara opened this issue Feb 12, 2025 · 0 comments
Open

T240516 Top-level const and Low-level const #11968

guevara opened this issue Feb 12, 2025 · 0 comments

Comments

@guevara
Copy link
Owner

guevara commented Feb 12, 2025

T240516 Top-level const and Low-level const



https://ift.tt/y1ckBrh



Li Miu


本篇分享详细解释一下 Top-level const 和 Low-level const 的概念。

Top-level 和 Low-level 指的是名称修饰符所处的位置,const 是最常见的修饰符,举一反三,便可知所有情况。

由例子切入理解:

p1 的类型为 a constant pointer to intp2 的类型为 a pointer to constant int。Top 和 Low 表示修饰符距实际类型的位置,前者修饰指针本身,后者修饰类型本身。因此,p1 可以改变 a 的值,但无法对指针再次绑定,p2 则完全相反。

大多数类型都支持 Top-level const,而 Low-level const 常出现于指针和引用类型。

首先应该着重强调的是引用类型。引用类型是个可以自动解引用的只读指针类型,下面两种是等价写法:

Modern C++ 风格的代码几乎很少需要显式地使用指针类型,引用类型使用起来要更加简便和安全。

引用类型相当于自动添加了 Top-level const,可以手动再添加 Low-level const。指针类型则是相当特殊的一类,它可以同时添加二者。

它们之间最大的不同在于,Top-level const 可能会被忽略,而 Low-level const 永远不会被忽略。

第一种情境是对象拷贝。

第二种情境是模板参数推导。

第三种情境是 auto 类型推导。

    </div></div></div></div><br>





via CppMore https://www.cppmore.com

February 12, 2025 at 03:37PM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant