www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 14696] New: destructor for temporary called before statement

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

          Issue ID: 14696
           Summary: destructor for temporary called before statement is
                    complete with ternary operator and alias this
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Keywords: wrong-code
          Severity: major
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: schveiguy yahoo.com

If a type's alias this is used as the parameter to a function, and that
instance is a temporary, it should not be destroyed before the call occurs.

However, if that type is part of ternary operator, the dtor is called FIRST.
Example:

import std.stdio;
struct S
{
    void *get() {return null;}
    ~this() { writeln("S.dtor");}
    alias get this;
}

S makes() { return S();}

void foo(void *x) { writeln("foo"); }

void main(string[] args)
{
    foo(args.length ? makes() : null);
}

The output:

S.dtor
foo

If, for example, S's dtor destroys the memory that is returned by get(), then
this will result in dangling pointer to destroyed memory being passed to foo.

Real life example:
https://github.com/D-Programming-Language/phobos/pull/3404#issuecomment-111704941

I'm uncertain what is required to make this happen. If I remove the ternary
expression, then the destructor is properly called after foo. But I don't know
if alias this is required.

--
Jun 13 2015