Why can you call the copy constructor passing in the object you are creating? (C ++) (gcc)

Possible duplicate:
std :: string x (x);

class A {}; int main() { A a(a); } 

It compiles.

gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)
g++ -o main main.cpp -Wall -w -ansi

I do not receive any warnings.

Why does this look like valid C ++?
Is it mentioned anywhere in the standard?
Are there any warning flags that can report this to gcc?

When a 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 << ai << '\n'; } 

: -482728464

What's going on here? Also, how can I prevent this from happening accidentally? - Is it possible to make a compiler error?

+8
c ++ copy-constructor class member
source share
1 answer

(ยง 3.3.2 / 1) The declaration point for the name immediately after its full declaration (section 8) and before its initializer (if any), except as noted below. [Example:

 int x = 12; { int x = x; } 

Here the second x is initialized with its own (undefined) value. -end example]

This applies to custom types such as your class A The copy constructor used is a standard, automatically generated compiler.

+10
source share

All Articles