简体   繁体   English

被变量作用域混淆-析构函数意外调用

[英]Confused by variable scope - destructor called unexpectedly

I have 3 classes, Fruit, Apple and Orange, with Fruit being the parent of both. 我有3个班级,水果,苹果和橘子,其中两个都是水果。 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的析构函数,该析构函数运行了Fruit所没有的清理代码。 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 . 您正在创建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. FruitApple之间的等级关系在这里无关紧要。

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. 这样可以更清楚地说明为什么~Apple()在分配结束时被调用。

Also note that: 另请注意:

Fruit f = Apple();

will perform object slicing , which makes it an anti-pattern. 将执行对象切片 ,使其成为反模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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