reference points to result of operation

Hi,

The following pseudo code seems to work (i.e., the values in "v1" are correct). However, I wonder whether it really is the right way to do it. My doubt is because actually "v1" is a reference, but it's not pointing to any existing object, only to the result of the subtraction of two objects. (As a matter of fact, to the subtraction of two references to two objects, but I guess that distinction is not important).
Can I do this safely or is this a risky thing to do?

CHit* hit1 = new Hit(x1, y1, z1, E1);
CHit* hit2 = new Hit(x2, y2, z2, E2);
// using method of CHit, defined as:
// const C3Vector& GetPosition() const;

const C3Vector& v1 = hit2->GetPosition() - hit1->GetPosition();

Cheers,

Machiel
When you bind a temporary object (such as the return value of a function) to a const reference the lifetime of the object is extended to that of the reference, so in other words it is safe, but why are you doing this? Why not just store it as a regular variable?

 
C3Vector v1 = hit2->GetPosition() - hit1->GetPosition();

Hi Peter,

Thank you for your help.

This happens inside a loop, so the same operation is repeated many times, until I find the optimal "v1". I thought this way I would avoid creating an entire C3Vector object for each iteration, then copying the result of the subtraction to it, and then removing it from the stack again. Am I wrong in thinking this?
Last edited on
Modern compilers are good at return value optimization so I don't think you need to worry about copies when returning local variables from functions.
https://en.wikipedia.org/wiki/Return_value_optimization
Topic archived. No new replies allowed.