Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder3.hal-mli.net!nx02.iad01.newshosting.com!newshosting.com!news-out.readnews.com!news-xxxfer.readnews.com!postnews.google.com!news3.google.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Ian Collins Newsgroups: comp.lang.c++ Subject: Re: mutable vs const_cast, which is better to modify field from const function? Date: Sat, 09 Jul 2011 19:28:18 +1200 Lines: 52 Message-ID: <97qea4F6tmU2@mid.individual.net> References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net w73xg/iMRiWOq/DMWVf+6wghjwHkBB2CXGrp6nmHZ83WiIe6Pa Cancel-Lock: sha1:bLxAiuMGvRtzNyVkNWVeXfnFi0I= User-Agent: Mozilla/5.0 (X11; U; SunOS i86pc; en-US; rv:1.9.2.9) Gecko/20101021 Lightning/1.0b2 Thunderbird/3.1.4 In-Reply-To: Xref: x330-a1.tempe.blueboxinc.net comp.lang.c++:7668 On 07/ 9/11 06:19 PM, Qi wrote: > It's not rare to lazy initialize member field in getter functions which > are const function. > > class SomeClass { > public: > MyObject * getMyObject() const { > if(! this->myObject) { > this->myObject = create the object; > } > > return this->myObject; > } You don't need all those "this->". > private: > MyObject * myObject; > }; > > To be able to modify myObject in the getter function, we can > either, > 1, Use mutable on myObject. > mutable MyObject * myObject; > or > 2, Use const_cast to cast away constness from "this". > const_cast(this)->myObject = create the object; > > Both methods have their own pros and cons, that's why I can't > decide which is better. How about: struct SomeClass { SomeClass() {} MyObject* getMyObject() const { static MyObject* myObject; if(!myObject) { myObject = new MyObject; } return myObject; } }; -- Ian Collins