DIP44

From D Wiki
Revision as of 23:57, 23 August 2013 by Quickfur (talk | contribs) (description)
Jump to: navigation, search
Title: scope(class) and scope(struct)
DIP: 44
Version: 1
Status: Draft
Created: 2013-08-23
Last Modified: 2013-08-23
Author: H. S. Teoh
Links:

DIP44: scope(class) and scope(struct)

Abstract

Extend scope guards to include class lifetime and struct lifetime, in order to solve the partially-constructed object problem.

Description

The syntax of scope(class) and scope(struct) follows that of the current scope guards. They are only allowed inside the body of the class/struct constructor:

class C {
    Resource res;
    this() {
        res = acquireResource();
        scope(class) res.release();
    }
}

struct S {
    Resource res;
    this() {
        res = acquireResource();
        scope(struct) res.release();
    }
}

When the class is destructed or the struct goes out of scope, the associated scope statements will be executed in reverse order of their execution in the constructor.

The intended usage is, as illustrated by the above example, is to perform cleanups of resources acquired in the constructor. While this can already be achieved by putting the corresponding code in the destructor, using the scope guard syntax is much cleaner and also avoids some pitfalls in the traditional approach, as the next section will explain.