copy constructor

Hallo
I know that C++ supports two forms of initialization: direct initialization, that places the initializer in parentheses, and copy initialization, that uses the = symbol:
<string str1("James Hillman"); //direct initialization>
<string str2 = "James Hillman"; //copy initialization>
In another example I’ve seen the copy constructor used with the parentheses, and not with = symbol:
<T *p = new T;>
<T a(*p); //copy constructor copies *p into a;>
This is confusing for me. What is the rule that let me know if the compiler is using the direct or copy form of initialization?

Thank you.
string str2 = "James Hillman"; //copy initialization

No, this using the const char* constructor of std::string.

1
2
some_type x = something_else; //is the same as
some_type x(something_else);


The copy constructor is basically a different name for a constructor that takes a const T& where T is the type of whatever you are constructing.
The terms mentioned by the OP are a valid technical concern. Although the compiler is expected to generate the same binary result, the meaning of the notation is (or once was) significant1.

Consider:
1
2
3
4
struct Y
{
    Y( int );
};

1
2
3
Y a( 1 );     // direct
Y b = Y( 2 ); // copy initialization
Y c = 3;      // copy initialization 


The variable a would be initialized using a direct invocation of the constructor. Supposedly, b and c would create a temporary, initialize the lvalue via copy construction, and the temporary would be destroyed. The compiler optimizes this away, so they are often thought to all be the same and practically speaking, they are.


1 This information can be verified in C++ Gotchas by Stephen C. Dewhurst, under Gotcha #56: Direct versus Copy Initialization.
Last edited on
OK, the question is subtle, but now is more evident.
Thank you.
Topic archived. No new replies allowed.