Issue with const

Jacob Carlborg doob at me.com
Mon Apr 9 07:49:06 PDT 2012


Say I have type and a function look like this:

class Foo
{
     void* data;

     Foo clone ()
     {
         auto c = new Foo;
         c.data = data;

         return c;
     }
}

void bar (Foo foo)
{
     auto c = foo.clone();
     ...
}

Since I'm not changing anything on "foo" I thought that it could be a 
good idea to declare it as const.

void bar (const Foo foo)
{
     auto c = foo.clone();
     ...
}

In this case I also have to make "clone" const as well. Which is fine 
sine "clone" doesn't change any of the fields.

class Foo
{
     void* data;

     Foo clone () const
     {
         auto c = new Foo;
         c.data = data;

         return c;
     }
}

But now when I compile this code I get this error:

Error: cannot implicitly convert expression (this.data) of type 
const(void*) to void*

Any idea how to solve this? Or would I need to drop const.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list