idup class
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 16 13:36:28 PDT 2014
On Fri, 16 May 2014 16:28:41 -0400, Joshua Niehus <jm.niehus at gmail.com>
wrote:
> trying to follow:
> http://ddili.org/ders/d.en/class.html
>
> //--- OSX 10.9 DMD 2.065
> module test;
>
> class Foo {
> int num;
>
> this(int num) {
> this.num = num;
> }
>
> Foo dup() const {
> return new Foo(this.num);
> }
>
> immutable(Foo) idup() const {
> return new immutable(Foo)(this.num);
> }
> }
>
> void main() {
> auto foo = new Foo(1);
> auto mfoo = foo.dup();
> auto ifoo = foo.idup();
> }
>
> * test.d(15): Error: mutable method test.Foo.this is not callable
> using a immutable object
> * test.d(15): Error: no constructor for Foo
> * Failed: ["dmd", "-v", "-o-", "test.d", "-I."]
> //---
>
> What am i missing?
your constructor needs the immutable tag.
this(int num) immutable ...
However, you can avoid much of this by tagging things as pure:
(untested, but just keep the internals the same)
class Foo
{
int num;
this(int num) pure {...}
Foo dup() const pure {...}
immutable(Foo) idup() const pure {...}
}
void main()
{
... // same implementation
}
Note that doing this, you do not need to have an idup, this should work:
immutable ifoo = foo.dup();
-Steve
More information about the Digitalmars-d-learn
mailing list