Reputation: 16402
I have 3 classes, Fruit, Apple and Orange, with Fruit being the parent of both. I have a static method where I do the following:
int32_t Fruit::frutificate(const Settings& settings) {
Fruit listener;
if (settings.has_domain_socket()) {
listener = Apple(settings);
} else {
listener = Orange(settings);
}
return uv_run(listener.loop, UV_RUN_DEFAULT);
}
What confuses me is that the destructor of Apple, which runs clean up code Fruit doesn't have, is called within the condition. Apple is a child of Fruit and Fruit is declared outside the condition so shouldn't the scope last until the return?
Upvotes: 1
Views: 137
Reputation: 302643
You are creating a temporary of type Apple
. It goes out of scope at the end of the expression that it is a part of - which is the assignment statement. When it goes out of scope, the destructor will get called. The hierarchical relationship between Fruit
and Apple
is irrelevant here.
If it helps, you can think of this block:
if (settings.has_domain_socket()) {
listener = Apple(settings);
}
as basically equivalent to:
if (settings.has_domain_socket()) {
Apple some_temporary_apple(settings);
listener = std::move(some_temporary_apple);
}
which may make it clearer as to why ~Apple()
gets called at the end of the assignment.
Also note that:
Fruit f = Apple();
will perform object slicing, which makes it an anti-pattern.
Upvotes: 6