Home >Backend Development >C++ >Why Does Top-Level Const on Non-Class Return Types Seem Redundant?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 07:56:02988browse

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>

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>

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>

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>

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!

Statement:
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