Possible Duplicate:
std::string x(x);
class A {};
int main() {
A a(a);
}
This compiles.
gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)
g++ -o main main.cpp -Wall -w -ansi
I receive no warnings.
Why does this appear to be valid C++?
Is this mentioned anywhere in the standard?
Are there warning flags that can report this for gcc?
When the class has member data, the data ends up random.
example:
#include <iostream>
class A {
public:
int i;
A() : i{6} {}
};
int main() {
A a(a);
std::cout << a.i << '\n';
}
output: -482728464
What’s going on here?
Also, how can I prevent myself from accidently doing this? – Is it possible to make it a compiler error?
This applies to user-defined types, such as your
class A, as well. The copy constructor used is the default one, auto-generated by the compiler.