Sense check: construction / deconstruction
Steven Schveighoffer
schveiguy at yahoo.com
Wed Apr 25 13:52:16 UTC 2018
On 4/25/18 5:51 AM, Jordan Wilson wrote:
> On Tuesday, 24 April 2018 at 23:49:14 UTC, Steven Schveighoffer wrote:
>> In the second case (b), you aren't including the db by value, so no
>> destructor is called from the GC. But this is dangerous, because db
>> stops existing after main exits, but b continues to exist in the GC,
>> so this is a dangling pointer.
>
> If I set the pointer to null, before (b) is collected, would that work?
More importantly, set it to null before Database goes out of scope.
This is what I'd recommend (if you want to go this path):
auto b = new B(&db);
scope(exit) b.db = null;
But I don't know why you wouldn't just use scoped.
>> In the third case, scoped specifically destroys c when main exits, and
>> you are not in the GC at that point.
>>
>> What the error message is telling you is you should manually clean up
>> the database directly instead of leaving it to the GC. What is the
>> correct path? probably the scoped!A version. Though I'm not sure what
>> making copies of the database does in that library.
>
> Ok I'll need to read the docs on scoped I think, but I think I understand.
>
> If I wanted db to be persistent, but have temporary objects reference db
> without triggering GC collection of the db, you would use scoped?
> Or is this a situation where it's better to pass the db in function
> calls to objects rather than set as a member of these objects?
In that case, using a pointer is OK, as long as you put the DB in thread
local storage (so it doesn't go out of scope).
Just put it at module level somewhere. In my projects, I have a pool of
connections that is used, and the pool is in TLS. When I want a
connection, I just grab the next one available, and it's reference
counted, so it's released back to the pool automatically whenever
anything goes out of scope. However, all my types are structs, and I
don't put them on the GC.
-Steve
More information about the Digitalmars-d-learn
mailing list