lvalue method

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Fri Oct 8 02:13:00 PDT 2010

On Fri, 08 Oct 2010 09:33:22 +0200, Benjamin Thaut wrote:

> Hi, I'm writing a vec4 math struct and I have a method of which the
> return value has to be a lvalue so I wonder which is the correct way to
> do this:
> vec4 Normalize() const { ... } //won't work, not a lvalue
> ref vec4 Normalize() const {
>    vec4 temp;
>    ...
>    return temp;
> } //will this lead to a segfault or not?

The compiler shouldn't even accept this.  When I try a similar thing, DMD 
says "Error: escaping reference to local variable temp".

> ref vec4 Normalize() const {
>    vec4* temp = new vec4;
>    ...
>    return *temp;
> } //ugly, don't want to allocate anything on the heap

This would work, since the variable is no longer on the stack and thus 
survives the return of the function.

> auto ref vec4 Normalize() const {
>    vec4 temp;
>    ...
>    return temp;
> } //will this lead to a segfault?

Well, that should compile, but it doesn't work the way you want.  'auto 
ref' means that the function returns by ref if the return expression is 
an lvalue *and it would not be a reference to a local or a parameter*.  
So for this example, your function would return by value, not by ref.

> Or do I need to do it totaly in some other way?

Yes, you do. :)  You are trying to create a variable on the stack, and 
return it by reference.  The problem is that when the function returns, 
its stack frame (the memory occupied by the function's local variables) 
is "released".  At that point the variable doesn't exist anymore, and any 
reference to it would be invalid.


More information about the Digitalmars-d-learn mailing list