scope() and FileConduit (D1 and Tango)

Bill Baxter wbaxter at gmail.com
Fri Oct 3 18:59:57 PDT 2008


On Sat, Oct 4, 2008 at 10:11 AM, Jarrett Billingsley
<jarrett.billingsley at gmail.com> wrote:
> On Fri, Oct 3, 2008 at 8:58 PM, Bill Baxter <wbaxter at gmail.com> wrote:
>> On Sat, Oct 4, 2008 at 7:08 AM, Jarrett Billingsley
>> <jarrett.billingsley at gmail.com> wrote:
>>> On Fri, Oct 3, 2008 at 4:57 PM, Nick Sabalausky <a at a.a> wrote:
>>>> I'd like some clarification on the way scope() works, and also Tango's
>>>> FileConduit. In the following function:
>>>>
>>>> void load(char[] infilename)
>>>> {
>>>>    auto file = new FileConduit(infilename);
>>>>    scope(exit) file.close();
>>>>
>>>>    // Load data
>>>> }
>>>>
>>>> What happens if infilename doesn't exist? Does FileConduit's constructor
>>>> throw an exception? If so, file.close() isn't called, is it?
>>>
>>> Yes, the ctor throws an exception.  No, file.close is never called.
>>> scope statements are only executed if execution reaches them
>>> successfully.
>>
>> Oh, ok I see what the issue is now.  I think this will do the right thing:
>>
>> void load(char[] infilename)
>> {
>>   FileConduit file;
>>   scope(exit) { if (file) file.close(); }
>>   file = new FileConduit(infilename);
>>    // Load data
>> }
>
> That's pretty much unnecessary, since in this code:
>
> auto file = new FileConduit(infilename);
> scope(exit) file.close();
>
> if FileConduit's constructor fails, there is no file to close, so
> there's no need to check for that.

Oh yeh.  Good point.

--bb


More information about the Digitalmars-d-learn mailing list