views:

78

answers:

1

Consider the following ways of declaring and initializing a variable of type C:

C c1;

C c2;
c2 = C();

C c3(C());

C c4 = C();

Are all of these completely equivalent to each other, or can some of these differ depending on the exact definition of C? (assuming it has public default and copy constructors).

+10  A: 

These mean:

C c1;   // default constructor

C c2;   // default constructor
c2 = C(); // default constructor followed by assignment

C c3(C());   // default constructor possibly followed by copy constructor

C c4 = C();  // default constructor possibly followed by copy constructor

Note the compiler can elide copy constructor calls. Are they equivalent? - well, it depends on what the copy constructor and assignment operator do.

anon
Note that it is important that even if the copy is elided, the requirements are checked. That is, if the copy constructor is not accessible (private/protected) at this level, 3 and 4 will fail to compile even if the copy constructor is never called.
David Rodríguez - dribeas
@David True, but in this case the question explicitly states that the copy constructor is public.
anon
So if the copy constructor were private, `c3` and `c4` wouldn't compile, but `c2` still would, right? (including the assignment). What about a call to `func(c2)` - would this also fail to compile with a private copy constructor?
romkyns
In case of C3 some compilers (at least Visual Studio) cannot differentiate `C c3(C());` from function declaration. You may need add extra brackets to avoid compiler warning: `C c3((C()));`
a1ex07
@rom Yes, it would, as would returning a C value.
anon