0

Suppose we have a struct named A declared this way:

struct A{
  ~A(){
     cout << "destructor called" << endl;
  }
}

and a main:

A create(){
  A variableToReturn;
  return variableToReturn;
}
int main() {
  A var1 = create();
  return 0;
}

is the destructor called even though we returned the variable from a function and so is the variable in main var1 defined or not? Same question arise if we return the variable from an operator such as:

A var1 = var2 + var3;
  • 4
    Lookup RVO and NVRO. – Tanveer Badar Jun 09 '22 at 07:12
  • 1
    Your code is fine, the compiler will take care of destroying and creating objects here. – Ulrich Eckhardt Jun 09 '22 at 07:14
  • Read a good C++ programming book, then [some C++ reference](https://en.cppreference.com/w/cpp), then [n3337](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) or something newer. Be aware of the [rule of five](https://cpppatterns.com/patterns/rule-of-five.html). Provide some [mre] in your next question – Basile Starynkevitch Jun 09 '22 at 07:15
  • Overloaded operators are normal functions, but with peculiar names. – molbdnilo Jun 09 '22 at 07:22

0 Answers0