I realise it can be const here and the thing will compile. But there’s this other idea kicking around that const methods are ‘thread-safe’ in some way, and clearly here, once you’ve got the pointer to ownedThing you could probably call a method on ownedThing that modifies it.
class C
{
public:
C() { ownedThing = new D();}
D * getOwnedThing() { return ownedThing; }
private:
ScopedPointer<D> ownedThing;
};
You can implement both and let the compiler choose:
D * getOwnedThing() { return ownedThing; }
const D * getOwnedThing() const { return ownedThing; }
getOwnedThing()->getProperty(); // will use the const, if getProperty() is a const method
getOwnedThing()->modify(); // will use the non const
In any case, simply marking methods “const” does not make anything thread safe. Hopefully you have not gotten that impression for somewhere.
The whole “since C++11 const means thread safe” thing hasn’t been always explained properly. It means that code using those const methods is now allowed to trust the methods are thread safe. The implementer of those const methods is still fully responsible for ensuring the const methods of the objects actually behave in a thread safe manner.
The pointer’s content might be completely unrelated to the class in the first place (e.g. if there’d be something like setOwnedObject(D*)), so formally the compiler assumes correctly that changing the D object pointed to doesn’t affect the class state.
No idea what is the best way to handle this. I used the duplicate const/non const approach but this isn’t very beautiful code if the pointer needs to be created somehow (e.g. via dynamic_cast) as it isn’t DRY.
Yep - I get that adding const to something doesn’t magically make it safe to use from multiple threads as long as no non-const methods are called (which I presume is where this const = thread-safe thing is going…)