TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Why don't compilers warn for const T f()?

1 pointsby jandeboevrie7 months ago

1 comment

lesserknowndan7 months ago
This article could perhaps do a better job of explaining what is talking about.<p>As some explanation, in C++ you have three general modes of returning a value:<p><pre><code> string function1(); string* function2(); string&amp; function3(); </code></pre> The first is return by value, i.e. a copy of the value is returned. The second returns a pointer, which presumably points to a string in memory somewhere. The third returns a reference, which is similar to a pointer except, in general, has the semantics that you should assume the object is either allocated on the stack or is owned by some other object and therefore should not be freed.<p><pre><code> const string function1(); const string* function2(); const string&amp; function3(); </code></pre> Adding a const constraint to a pointer or reference is useful because code that receives the returned value is prevented from modifying the contents of the string or calling any of its methods that aren&#x27;t themselves declared as const.<p>The point of this article is that when returning a copy of a value, it is largely pointless to prevent the caller from modifying the returned copy; and therefore that compilers should warn when this is done.