[cfe-dev] Ownership of Stmts and Exprs, and destroying them

Doug Gregor doug.gregor at gmail.com
Tue Nov 25 21:03:59 PST 2008


On Tue, Nov 25, 2008 at 2:00 PM, Howard Hinnant <hhinnant at apple.com> wrote:
>
> On Nov 25, 2008, at 1:47 PM, Chris Lattner wrote:
>
>> On Nov 24, 2008, at 7:36 PM, Doug Gregor wrote:
>>>>> Similarly for ExprResult and
>>>>> friends. That way, the type system enforces our ownership model
>>>>> (transfer into Sema for the parameters of ActOn*, transfer out of
>>>>> Sema
>>>>> on return), and we're safe from early exits.
>>>>
>>>> ExprResult is just a pair of success + pointer.  The actions in
>>>> Sema are
>>>> only called in the success case.
>>>
>>> Of course. But ExprResult also (implicitly!) carries with it the
>>> ownership of the pointer, and that's not at all clear now.
>>
>> Ok, I agree with you.  However, making the contract more clear seems
>> conceptually separate from making sema or the parser not leak.  Are
>> you saying that both problems could be solved in the same way?
>
> I don't want to speak for Doug, but here is some working C++0X demo
> code which I believe demonstrates.
[snip code]

Yeah, that's the idea. To narrate a bit more: when there's a clear
ownership model that's tied to the type system, it becomes very easy
to enforce proper memory management. By using unique_ptr-like smart
pointers in the interface, we enforce the transfer of ownership:
passing an expression to one of Action's methods via a unique_ptr
interface transfers ownership into the implementor of Action. Since,
by default, that smart pointer will delete what it's storing, even an
empty Action method implementation will not leak. It's the same thing
with returning a unique_ptr-like object from the Action routines,
e.g., from ActOnCallExpr: if ExprResult is a smart pointer, we're
transferring ownership back from the Action implementation to the
parser. The parser can either re-transfer ownership to the Action
implementation (by passing the expression back through an Action
method) or just leave it alone, in which case it will be deallocated
automatically.

The end result, while not idiot-proof, should mean that we have our
memory management on solid footing even in the tricky cases of failed
parses, semantic disasters, etc. Plus, the whole scheme works even in
the face of exceptions.

  - Doug



More information about the cfe-dev mailing list