简体   繁体   中英

Confused by variable scope - destructor called unexpectedly

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM