Newsgroups: comp.lang.c++ Path: utzoo!censor!geac!alias!earth!rae From: Reid Ellis Subject: more on "foo & operator+ (const foo&)" Message-ID: Sender: Reid Ellis Reply-To: Reid Ellis Organization: Alias Research, Inc. Toronto ON Canada References: <11759@hubcap.clemson.edu> <1939@m1.cs.man.ac.uk> Date: 27 Nov 90 05:40:28 GMT In fuchs@it.uka.de (Harald Fuchs) writes: >I _never_ use > foo& operator+ (const foo&, const foo&) >(returning a reference) because this can lead to dangling references. >The returned value can't refer to an object on the stack because the >stack is popped when returning from operator+. It cannot refer to a >local static variable inside operator+ because in this case something like > foo f1 = f2 + f3 + f4; >would give the wrong result. Only if your operator+() assumed that none of the parameters could ever be the result of a previous addition. I agree that this technique should be avoided if possible, but if you need the speed, you can do it if you're careful. e.g., for an integer class "Tint": Tint& operator+(const Tint &left, const Tint &right) { static Tint stat; stat.value = left.value + right.value; return stat; } This will never have a problem with either of 'l' or 'r' being the result of a previous '+' -- i.e., a reference to 's'. But I should state again that I agree that this should be avoided if possible. Be sure that doing this will really speed up your code by profiling it before introducing something that could cause subtle errors. Reid -- Reid Ellis 176 Brookbanks Drive, Toronto ON, M3A 2T5 Canada rae@gpu.utcs.toronto.edu || rae%alias@csri.toronto.edu CDA0610@applelink.apple.com || +1 416 446 1644