Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call the destructor twice #1101

Closed
liziyi75 opened this issue Jan 4, 2024 · 1 comment
Closed

Call the destructor twice #1101

liziyi75 opened this issue Jan 4, 2024 · 1 comment
Assignees
Labels
question open question solved available upstream or in a branch

Comments

@liziyi75
Copy link

liziyi75 commented Jan 4, 2024

https://godbolt.org/z/b8MfeaWq5

@skypjack skypjack self-assigned this Jan 8, 2024
@skypjack skypjack added the question open question label Jan 8, 2024
@skypjack
Copy link
Owner

skypjack commented Jan 8, 2024

EnTT uses a simplified swap-and-pop policy by default (unless you enable something like the in-place delete).
The internals are a little more complicated than what I'm going to describe here but imagine the following for a moment:

  • You swap the last element with the one to remove. Swapping involves a third (and temporary) element that is discarded immediately after. First destructor invoked.
  • You pop the last element in the set. Second destructor invoked.

Here we go with your destructors. Two elements, two invocations. That's all.
The fact that you've a single element doesn't really matter. EnTT doesn't place all this after an if that only works in a single case. It would be a waste of cpu cycles for nothing. Instead, the library uses a safe approach that works in all cases.


That being said and for the sake of curiosity, EnTT works in a slightly different manner internally but the final result is similar.
What happens is that the last element is moved into a call to std:.exchange with the element to drop which is returned rather than discarded immediately. Then we pop the last (moved-from) element and you've the first destructor invoked. Finally we let the element to discard go out of scope and you have the second destructor invoked.
Why it's that complicated? Well, all this is meant to support re-entrant destructors. A rather sophisticated feature that most users don't use (and not even know about actually) but which is also very powerful in case you need it.

@skypjack skypjack added the solved available upstream or in a branch label Jan 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question open question solved available upstream or in a branch
Projects
None yet
Development

No branches or pull requests

2 participants