Bug 13336 – auto ref return deduced to be ref despite return value coercion
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-08-19T21:31:00Z
Last change time
2015-02-18T03:40:26Z
Keywords
pull, wrong-code
Assigned to
nobody
Creator
peter.alexander.au
Comments
Comment #0 by peter.alexander.au — 2014-08-19T21:31:11Z
------------------------
int sx;
double sy;
auto ref foo()
{
if (1)
return sx;
return sy;
}
------------------------
foo is determined to return a 'ref double', even though sx is not a double. It is cast to a double and a ref to the temporary is returned.
Expected behaviour: When common-type coercions are involved, auto ref should deduce to be non-ref otherwise the code becomes unsafe and surprising.
The spec doesn't say anything about this, it just says "The lexically first ReturnStatement determines the ref-ness of a function".
Comment #1 by peter.alexander.au — 2014-08-19T21:59:29Z
You can break the type system using this:
class Animal {}
class Cat : Animal {}
class Dog : Animal {}
Animal animal;
Cat cat;
auto ref choose()
{
return cat;
return animal;
}
void main()
{
import std.stdio;
choose() = new Dog();
writeln("cat is a ", typeid(cat));
}
Prints "cat is a Dog"