D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 4068 - Returning references to const members yield error message
Summary: Returning references to const members yield error message
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: Other Windows
: P2 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2010-04-05 05:57 UTC by Simen Kjaeraas
Modified: 2014-02-15 02:46 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Simen Kjaeraas 2010-04-05 05:57:30 UTC
The following should IMO compile:

struct S {
  const int n;
  const ref int bar( ) {
    return n;
  }
}

It fails on the line 'return n;', with the message 'Error: can only initialize const member n inside constructor'

The same behavior exists with immutable members and references.
Comment 1 Steven Schveighoffer 2010-04-05 07:13:07 UTC
This probably is invalid, because the const in that position applies to the this pointer.  It's equivalent to:

ref int bar() const {


To get the desired behavior, use parentheses:

ref const(int) bar() {

These kinds of errors are why I think allowing const at the beginning of the function should be deprecated.

One strange thing, this also has same error:

ref const int bar() {

It would follow logically that if const applies to the function bar and not the return value, then ref applies to the function bar as well, but it obviously only applies to the return value.
Comment 2 Simen Kjaeraas 2010-04-05 10:09:50 UTC
(In reply to comment #1)
> This probably is invalid, because the const in that position applies to the
> this pointer.  It's equivalent to:
> [...]
> These kinds of errors are why I think allowing const at the beginning of the
> function should be deprecated.

Indeed. Closing this one.