Home > Backend Development > C++ > body text

Why Does Top-Level Const on Non-Class Return Types Seem Redundant?

Linda Hamilton
Release: 2024-11-04 07:56:02
Original
930 people have browsed it

Why Does Top-Level Const on Non-Class Return Types Seem Redundant?

Do Non-Class Return Types Benefit from Const?

In C , the usage of const has been emphasized as a best practice for immutable data handling. However, it may seem that qualifying non-class return types with const yields no noticeable difference:

<code class="cpp">int foo() { }
const int foo() { }</code>
Copy after login

Why, then, does this distinction exist, as exemplified by the Bigint class:

<code class="cpp">int& operator[](const int index);
const int operator[](const int index) const;</code>
Copy after login

Explanation:

Top-level const qualifiers applied to the return types of non-class functions are effectively ignored, rendering the two declarations above identical. However, this is not the case for references:

<code class="cpp">int& operator[](int index);
int const& operator[](int index) const;</code>
Copy after login

In such scenarios, the distinction is meaningful.

Furthermore, top-level const qualifiers on return types are similarly ignored in function declarations.

The relevance of const qualifiers also extends to class return types. If a function returns T const, any attempt to invoke non-const functions on the returned object will result in an error, as illustrated below:

<code class="cpp">class Test {
public:
    void f();
    void g() const;
};

Test ff();
Test const gg();

ff().f();             // legal
ff().g();             // legal
gg().f();             // illegal
gg().g();             // legal</code>
Copy after login

The above is the detailed content of Why Does Top-Level Const on Non-Class Return Types Seem Redundant?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!