Bug 6427 – Templated ctor cannot set immutable member variables

Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2011-08-02T06:39:00Z
Last change time
2011-08-03T07:37:22Z
Assigned to
nobody
Creator
simendsjo

Comments

Comment #0 by simendsjo — 2011-08-02T06:39:49Z
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 by issues.dlang — 2011-08-02T11:06:42Z
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 by issues.dlang — 2011-08-02T12:45:15Z
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 by yebblies — 2011-08-03T07:37:22Z
*** This issue has been marked as a duplicate of issue 6355 ***