Thread overview | |||||
---|---|---|---|---|---|
|
March 13, 2019 Returning reference: why this works? | ||||
---|---|---|---|---|
| ||||
import std.stdio; struct S { int x; } ref S func1(ref S i) // i is reference { return i; } ref S func2(S i) // i is not reference { return func1(i); // Works! Possibility to return reference to local object i? //return i; // Error: returning i escapes a reference to parameter i } void main() { auto ret = func2(S(2)); writeln(ret); // "S(2)" } |
March 13, 2019 Re: Returning reference: why this works? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Denis Feklushkin | On Wednesday, 13 March 2019 at 20:57:13 UTC, Denis Feklushkin wrote:
> import std.stdio;
>
> struct S { int x; }
>
> ref S func1(ref S i) // i is reference
> {
> return i;
> }
>
> ref S func2(S i) // i is not reference
> {
> return func1(i); // Works! Possibility to return reference to local object i?
Indeed, you're invoking UB here. With compiler flag `-dip25` that code no longer compiles.
-Johan
|
March 13, 2019 Re: Returning reference: why this works? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Johan Engelen | On Wednesday, 13 March 2019 at 21:04:01 UTC, Johan Engelen wrote:
> On Wednesday, 13 March 2019 at 20:57:13 UTC, Denis Feklushkin wrote:
>> import std.stdio;
>>
>> struct S { int x; }
>>
>> ref S func1(ref S i) // i is reference
>> {
>> return i;
>> }
>>
>> ref S func2(S i) // i is not reference
>> {
>> return func1(i); // Works! Possibility to return reference to local object i?
>
> Indeed, you're invoking UB here. With compiler flag `-dip25` that code no longer compiles.
>
> -Johan
Oh, very unexpected! Thank you very much!
|
Copyright © 1999-2021 by the D Language Foundation