Mutable


#1
    LibraryDiskFile(const File & location, const LibraryFile::Ptr parent)

    :

    diskfile(location),

    parent(parent)

    {}

    LibraryFile::Ptr getChildFile(const String & name)

    {

        const File f = diskfile.getChildFile(name);

        LibraryDiskFile * df = new LibraryDiskFile(f, LibraryFile::Ptr(this));

        return df;

    }


    LibraryFile::Ptr getChildFile(const String & name) const override

    {

        const File f = diskfile.getChildFile(name);

        LibraryDiskFile * df = new LibraryDiskFile(f, LibraryFile::Ptr(this));

        return df;

    }

The second version of getChildFile() fail to compile.  A const problem.  

The whole thing is ReferenceCountedObjectPtrs.  Is the right solution a ReferenceCountedObjectPtrConst, const_cast? Drop all the const qualifiers, even though it's basically const?  I tried: 

ReferenceCountedObjectPtr<const LibraryFile> just in case, but it gets into trouble in the template because a ReferenceCountedObject is not really const when it comes to the reference counting. Is that a valid use for mutable though really?

Thoughts?


#2

Interesting question!

Herb Sutter did a good talk recently suggesting that we should start thinking about const/mutable in terms of thread-safety, i.e. it's ok for something to be marked const and use mutability internally if the function is thread-safe. So in the case of a ReferenceCountedObjectPtr, it would sort of be OK for it to take a const object because it should be thread-safe (since it uses atomics), even though it clearly mutates the object, and may even delete it.


#3

Yeah.  I felt like I was getting into some C++ language beard stroking moment.  And now you mention Herb ... not that he's got much of a beard, but definitely involved in the stroking.

I might do a const_cast for the moment.  I don't think I'm going to go to jail for it...given that we think it'd be reasonable for the only field that's changing to be mutable.


#4

Yeah, I think no jury would convict you for using a const_cast in self-defence under the circumstances.


#5

I think that's the second ever const_cast in my entire life...and the other one was a textbook correct one.  

This one might need a C++ lawyer on it.

I suppose the actual fix is for ReferenceCountedObjectPtr to allow pointing to a const object by the careful use of mutable?

I'm struggling a bit with the inner philosphical meaning of const now.