3

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).

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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 True, but in this case the question explicitly states that the copy constructor is public.
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?
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()));
@rom Yes, it would, as would returning a C value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.