c++ - In which cases is it unsafe to (const) reference a return value? -


i tend use following notation lot:

const datum& d = a.calc(); // continue use d 

this works when result of calc on stack, see http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/. though compilers optimize here, feels nice explicitly avoid temporary objects.

today realized, content of d became invalid after data written member of a. in particular case function returned reference member, unrelated write however. this:

const datum& d = a.get(); // ... operation ... a.somedata = datum2(); // d invalid. 

again, somedata has nothing d or get() here.

now ask myself:

  1. which side-effects lead invalidation?
  2. is bad-practice assign return values const reference? (especially when don't know interior of function)

my application single-threaded except qt gui-thread.

which side-effects lead invalidation?

holding reference internal state of class (i.e., versus extending lifetime of temporary) , calling non-const member functions may potentially invalidate reference.

is bad-practice assign return values const reference? (especially when don't know interior of function)

i bad practice hold reference internal state of class instance, mutating class instance, , continuing use original reference (unless documented non-const functions don't invalidate reference)


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

mysql - FireDac error 314 - but DLLs are in program directory -