D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 6427 - Templated ctor cannot set immutable member variables
Summary: Templated ctor cannot set immutable member variables
Status: RESOLVED DUPLICATE of issue 6355
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2011-08-02 06:39 UTC by simendsjo
Modified: 2011-08-03 07:37 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description simendsjo 2011-08-02 06:39:49 UTC
struct S {
    immutable int v;
    this()(int v) {
        this.v = v;
    }
}

void main() {
    S s = S(1);
}

Error: can only initialize const member v inside constructor
Error: template instance t.S.__ctor!(int) error instantiating
Comment 1 Jonathan M Davis 2011-08-02 11:06:42 UTC
1. This compiles with the current compiler on github.

2. I'm not even 100% sure this is supposed to compile, since the constructor isn't immutable. That might only be necessary when the whole struct is immutable though. I don't remember for sure and would have to check in TDPL (which I don't have on me at the moment).

3. While this should certainly compile correctly based on the language spec (or not compile depending on the spec). I would serious advise against having const or immutable variables in a struct, since you can then never assign to them even if they're not const or immutable. If they're on the heap, it's not as big a deal, but a struct like S would be useless in arrays (since all of the values would be stuck as S.init) and every instance of it would be effectively immutable regardless of whether the object itself was typed as immutable or not.
Comment 2 Jonathan M Davis 2011-08-02 12:45:15 UTC
Okay. It looks like immutable constructors only apply to when the struct or class itself that you're constructing is immutable. So, this should definitely compile. And it does on the current version of the compiler. So, if it doesn't compile on 2.054, then this it was fixed since the release. I'd close it, but we might want it end the changelog, so it's probably better that someone who actually works on the compiler closes the bug. Regardless, it works with the latest version of the compiler, so 2.055 shouldn't have this bug.
Comment 3 yebblies 2011-08-03 07:37:22 UTC

*** This issue has been marked as a duplicate of issue 6355 ***