【问题标题】:There's one constructor, but two destructors [duplicate]有一个构造函数,但有两个析构函数[重复]
【发布时间】:2020-04-26 12:32:52
【问题描述】:

我花了一些时间才得到错误,但仍然不知道如何解决它

正如代码中显示的那样,只有一个构造函数调用,但它调用了两次析构函数

代码:

struct A
{
  A()
  {
      std::cout << "C'tor" << std::endl;
  }

  A(A&&)
  {
      std::cout << "M'tor" << std::endl;
  }

  A(const A&) = delete;
  A& operator=(const A&) = delete;
  A& operator=(A&&) = delete;

  ~A()
  {
      std::cout << "D'tor" << std::endl;
  }
};

int main()
{
    auto lambda = [](int i){
        A a;
        if (i == 0)
            return std::move(a);
    };

    lambda(1);
    return 0;
}

输出:

C'tor                                                                                                                                                                        
D'tor                                                                                                                                                                        
D'tor

怎么会这样? 编译器至少应该为我生成警告吗? 你怎么看?

【问题讨论】:

    标签: c++ oop gcc compilation


    【解决方案1】:

    lambda 的返回类型推断为A,但只要i != 0 就不会返回任何内容,就像您的示例一样。

    从非 void 函数不返回任何内容是 Undefined Behavior,即任何事情都可能发生。

    【讨论】:

      【解决方案2】:

      @pasbi 是对的,C++2a(GNU) 编译器明确警告了这一点:

      prog.cc: In lambda function:
      prog.cc:30:29: warning: moving a local object in a return statement prevents copy elision [-Wpessimizing-move]
      30 |             return std::move(a);
        |                    ~~~~~~~~~^~~
      prog.cc:30:29: note: remove 'std::move' call
      prog.cc:31:5: warning: control reaches end of non-void function [-Wreturn-type]
      31 |     };
        |     ^
      

      【讨论】:

        猜你喜欢
        • 2014-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-20
        • 1970-01-01
        • 2015-07-02
        • 1970-01-01
        • 2021-03-22
        相关资源
        最近更新 更多