Hacker News new | past | comments | ask | show | jobs | submit login
Why don't compilers warn for const T f()? (quuxplusone.github.io)
1 point by jandeboevrie 4 months ago | hide | past | favorite | 1 comment



This article could perhaps do a better job of explaining what is talking about.

As some explanation, in C++ you have three general modes of returning a value:

  string  function1();
  string* function2();
  string& function3();
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.

  const string  function1();
  const string* function2();
  const string& function3();
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't themselves declared as const.

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.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: