Re: mutable vs const_cast, which is better to modify field from const function?
On Jul 9, 8:50 am, Qi <n...@no.com> wrote:
On 2011-7-9 15:20, Narinder wrote:
struct MyObject{};
struct SomeClass
{
SomeClass():myObject(0){}
const MyObject * getMyObject()const
{
return getMyObject_impl();
}
MyObject * getMyObject()
{
return getMyObject_impl();
}
private:
const MyObject * getMyObject_impl()const
{
if(!myObject)
{
myObject = new MyObject();
}
return myObject;
}
MyObject * getMyObject_impl()
{
if(!myObject)
{
myObject = new MyObject();
}
return myObject;
}
mutable MyObject * myObject;
};
-------------------------------------------------
So as long as all your other member functions access myObject via the
getMyObject_impl methods it should be ok.
First, sorry that I forgot the "const" in the return of the getter.
I did mean const MyObject * getMyObject()const.
Back to my question, seems you are suggesting to use "mutable", right?
--
WQ
seems you are suggesting to use "mutable", right?
Yes I am, but at the same time if it's only ever accessed via the
private impl methods than effectively it's not mutable for your other
member functions. I would stay away from const_cast, I use it only in
debug specific code ( eg to make certain views available into const
data type to the debugger).
In the end you want your pointer to be mutable only for the
initialiser method, so, make it only mutable for the initialiser
method, which in my case are the private impl methods.
You could go one step further and encompass your pointer in a class
of it's own.
------------------------------------------
struct MyObject{};
struct MyObjectWrapper
{
MyObjectWrapper():myObject(0){}
const MyObject * getMyObject_impl()const
{
if(!myObject)
{
myObject = new MyObject();
}
return myObject;
}
MyObject * getMyObject_impl()
{
if(!myObject)
{
myObject = new MyObject();
}
return myObject;
}
private:
mutable MyObject * myObject;
};
struct SomeClass
{
const MyObject * getMyObject()const
{
return myObject.getMyObject_impl();
}
MyObject * getMyObject()
{
return myObject.getMyObject_impl();
}
private:
MyObjectWrapper myObject;
};
------------------------------------------