c++ - What is the best practice regarding const instance methods? -


The answer to the accepted answer indicates that a member will return a non-contact reference by frequency method compiled (one Without artists or members capable of making variable changes), a common best practice discussion of the questions const constant methods has been discussed.

For the future generation, here is the basic question:

If I have an object with a geller who gives non-concent references, for example:

  SomeObject & amp; SomeOtherObject :: foo () {someObjectInstance return; }  

Should it be constrained? Obviously, this call does not modify the object, but the caller can modify some object instances, which will change the example of some other objects.

I think my question really is " what exactly is a member method? " does this a) the call will not mutate the object only or B) call There may be no change in the object during, or as a result of the returned reference / pointers, warnings for those who do const_casts).

In a different form, I currently need to add it where I call const.

  const SomeObject & amp; SomeOtherObject :: constFoo () console {someObjectInstance return}; }  

for staying on a secure side, because I am reluctant to do it

  SomeObject & amp; Some other objects: foo () const {returnObjectInstance; }  

Even if it makes my life easier in some places.

const (when applied to a member function) Useful as a means of self-document. It is a contract with calling code that this function will not modify the external state (i.e. there is no side effect).

The compilier receives all the members by creating a const member inside the task effectively when constituting it properly

It is not unusual to look like code:

  const SomeObject & amp; SomeOtherObject :: constFoo () console; SomeObject & amp; SomeOtherObject :: constFoo (); The following will not be compiled (MSVC 9 and GCC 3.4.4)  
  some objects & amp; SomeOtherObject :: constFoo () console {someObjectInstance return}; }  

You can hack the casting around the above error:

  SomeObject & amp; SomeOtherObject :: constFoo () Const {Return (some object); SomeObjectInstance; }  

But it surely breaks the agreement with the users of your code that you will not change some other object instance.

To be able to avoid some object instance unstable artists, but in the end it is not really good.


Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -