RAII pointers

Stanislav Blinov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 3 14:16:08 PDT 2017


On Saturday, 3 June 2017 at 20:53:05 UTC, Moritz Maxeiner wrote:
> On Saturday, 3 June 2017 at 20:25:22 UTC, Stanislav Blinov 
> wrote:
>> On Saturday, 3 June 2017 at 20:13:30 UTC, Moritz Maxeiner 
>> wrote:
>>
>>> Calling std.algorithm.move is explicit programmer intent, I 
>>> consider that about as accidental as calling memcpy with a 
>>> source full of zeroes.
>>> In any case, having that check in the destructor is fairly 
>>> cheap, so better safe than sorry (and include it).
>>
>> Yes, it's explicit. Destructor call is still implicit though, 
>> and it better not be performing null dereference or something 
>> equally nasty :)
>
> Quite, but if you backtrack to my initial statement, it was 
> about ptr not being/becoming null (implicitly) in the first 
> place, which *might* allow you to skip the check (if you don't 
> set it to null via external means, such as memcpy, move, etc).

It's only true as long as you have full control of the source. 
Once you're using libraries and generic code, it's possible that 
it's out of your hands:

import core.stdc.stdio;
import std.exception;

// external library
struct RingBuffer(T,size_t size) {
     T[size] values = T.init; // the culprit
     // interface snipped...
}

// own code
struct FileWrapper {
     FILE* file;

     @disable this();
     @disable this(this);

     this(FILE* file) {
         enforce(file);
         this.file = file;
     }

     ~this() {
         fclose(file);
     }
}

void main() {
     // whoops, segfault
     RingBuffer!(FileWrapper,8) container;
}



More information about the Digitalmars-d-learn mailing list