As far as I know, thrown objects are copied by default. So the copy constructor should be called when I throw an object. I also know that the compiler may optimize and elide the copying. I have a simple program here where I'm throwing a class called X. It's expected that if I make the class non-copyable, the object can't be thrown. But something unexpected happens. If I delete the copy constructor, the compiler complains about that. If I comment the deletion of the copy constructor and delete the move constructor, the complier complains about deleting the move constructor. the code:
class X
{
public:
int code;
X(int code) : code(code) {}
//X(X&) = delete;
//X(X&&) = delete;
};
void func()
{
X x(4);
throw x;
}
int main() { }
The error when I delete the copy constructor:
main.cpp: In function ‘void func()’:
main.cpp:13:11: error: use of deleted function ‘X::X(X&)’
throw x;
^
The error when I delete the move constructor:
main.cpp: In function ‘void func()’:
main.cpp:13:11: error: use of deleted function ‘X::X(X&&)’
throw x;
^
Can someone explain why this is happening?
Edit: If I delete the copy constructor and provide an implementation for the move constructor, the code works fine. Whereas if I delete the move constructor and provide an Implementation for the copy constructor, I still get the same error. Why can't I delete the move constructor?
code:
class X
{
public:
int code;
X(int code) : code(code) {}
X(X&) = default;
X(X&&) = delete;
};
void func()
{
X x(5);
throw x;
}
int main() { }
error:
main.cpp: In function ‘void func()’:
main.cpp:13:11: error: use of deleted function ‘X::X(X&&)’
throw x;
^