I have a piece of code
#include <iostream>
class A {
public:
A() {
std::cout << "Default constructor" << std::endl;
}
A(const A & other)
{
std::cout << "Copy constructor" << std::endl;
}
A(A && other)
{
std::cout << "Move constructor" << std::endl;
}
~A()
{
std::cout << "Destructor" << std::endl;
}
private:
int i;
};
A && f()
{
return A();
}
int main() {
A a = f();
}
I tried running it and the output turns out to be
Default constructor
Destructor
Move constructor
Destructor
My question is Why is destructor is called before the moved constructor? Does this also mean that second object was constructed with a destroyed value ?
Returning a local variable from A && f()
has the same problem as A & f()
. They are both references. By the time you construct a
in main()
, the local variable has been destroyed. This results in a reference to a destroyed instance leading to undefined behavior.
If you want to move A()
from f()
to a
in main
simply return by value. Try using the following :
A f() {
return A();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With