Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There's one constructor, but two destructors [duplicate]

It took me some time to get the error but still can't know how to solve it

As it appears at the code there's only one constructor call but it calls the destructor twice

Code:

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;
}

Output:

C'tor                                                                                                                                                                        
D'tor                                                                                                                                                                        
D'tor

How can that happen? should the compiler could at the very least generate a warning for me? What do you think?

like image 901
Gils Avatar asked Mar 14 '26 05:03

Gils


1 Answers

The return type of lambda is deduced to be A, but nothing is returned as long as i != 0, like in your example.

Returning nothing from a non-void function is Undefined Behavior, i.e., anything can happen.

like image 94
pasbi Avatar answered Mar 15 '26 21:03

pasbi