Struct default constructor - need some kind of solution for C++ interop

Walter Bright via Digitalmars-d digitalmars-d at puremagic.com
Wed Sep 7 15:52:04 PDT 2016


On 9/7/2016 2:08 PM, deadalnix wrote:
> It is clear at this point that structures with obligatory initialization are
> necessary. For C++ but not only.

If not interfacing to C++, why?

> Right now, all dtors need to make sure that the
> .init state is valid, which can be a performance problem (you need to add
> runtime checks to know if you actually need to destroy a resource).

Is:

     if (resource != null)
         resource.destroy();

v.s.:

     resource.destroy();

so onerous? It's one TST/JNE pair for a value loaded into a register anyway. And 
with a default constructor, there's all that code added to deal with the 
constructor failing and throwing.

Besides, you can still write:

     struct S {
         Resource resource;

         Resource builder() {
             S s;
             s.resource = new Resource();
             return s;
         }

         ~this() {
             assert(resource);  // ensure user used builder()
             resource.destroy();
         }
     }


More information about the Digitalmars-d mailing list