[Issue 12226] functions can return local stack-allocated objects by reference

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Sat Jan 10 22:39:30 PST 2015


https://issues.dlang.org/show_bug.cgi?id=12226

--- Comment #1 from Kenji Hara <k.hara.pg at gmail.com> ---
(In reply to badlink from comment #0)
> Sample code: http://pastebin.com/rvcNdjAE

All sample code should be attached in bugzilla, or directly written in comment.

----------------
import std.stdio;

void main()
{
    auto a = Vec3f([0, 0, 0]);
    a += a * 0;
    writeln(a.array); // prints random values like [-1.13483, 4.2039e-45,
-1.13482]
    assert(a == Vec3f([0, 0, 0])); // fails
}

alias Vector!(3, float) Vec3f;
struct Vector(int size, T)
{
    T[size] array;

    auto ref opBinary(string op)(T rhs) const
    if (op == "+" || op == "-" || op == "*" || op == "/")
    {
        Vector vector = this;
        mixin("return vector" ~ op ~ "= rhs;");
    }

    auto ref opOpAssign(string op)(T rhs)
    if (op == "+" || op == "-" || op == "*" || op == "/")
    {
        mixin("array[] " ~ op ~ "= rhs;");
        return this;
    }

    auto opOpAssign(string op)(const ref Vector rhs)
    // auto opOpAssign(string op)(const Vector rhs) // witouth ref everything
works
    if (op == "+" || op == "-")
    {
        mixin("array[] " ~ op ~ "= rhs.array[];");
        return this;
    }
}
----------------

--


More information about the Digitalmars-d-bugs mailing list