问题
I am curious about what is happening in this code I wrote almost by mistake:
#include <iostream>
class Test
{
public:
Test() {
std::cout << "Default constructor";
a= 10;
}
int a;
};
int main() {
Test obj(obj);
std::cout << obj.a << std::endl;
}
It compiles in gcc without warnings of any kind (using -Wall -Werror). Executing it only prints garbage.
If I am not mistaken, this is calling the implicit copy-constructor on itself, without ever initialising. I am curious about what the copy-constructor would do in such a situation, but gdb will not stop in that line (breakpoints set to that line jump to the next one).
Everything breaks if "complex" attributes are added to the class (like a std::string
), probably because of how the '=' operator is overloaded for such classes.
Is my hypothesis correct? Why doesn't gdb stop in that line? Why no warnings when calling a copy constructor with an uninitialised object?
回答1:
Since you have a member variable of type int
, whose indeterminate value is copied to itself, the code is technically Undefined Behavior.
However, in practice, with current computers nothing bad will happen. But on the third hand, nothing good happens either.
Regarding warnings, that's a Quality Of Implementation issue. The C++ standard has nothing to say about that.
来源:https://stackoverflow.com/questions/28590937/calling-copy-constructor-on-yourself