转自:
copy initialization
Initializes an object from another object
Syntax
T object = other ; | (1) | ||||||||
f( other) ; | (2) | ||||||||
return other; | (3) | ||||||||
catch ( T other) ; | (4) | ||||||||
T array [ N ] = { other }; | (5) | ||||||||
Explanation
Copy initialization is performed in the following situations:
The effects of copy initialization are:
- If
T
is a class type and the type of other is cv-unqualified version ofT
or a class derived fromT
, the constructors ofT
are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.
- If
T
is a class type, and the type of other is different, or ifT
is non-class type, but the type of other is a class type, that can convert from the type of other toT
are examined and the best one is selected through overload resolution. The result of the conversion, which is a prvalue temporary of the destination type, is then used to the object. The last step is usually and the result of the conversion function is constructed directly in the memory allocated for the target object, but the copy constructor is required to be accessible even though it's not used.
- Otherwise (if neither
T
nor the type of other are class types), are used, if necessary, to convert the value of other to the cv-unqualified version ofT
.
Notes
Copy-initialization is less permissive than direct-initialization: copy-initialization only considers non-explicit constructors and user-defined conversion functions.
If other is an rvalue expression, will be selected by overload resolution and called during copy-initialization.
is defined in terms of copy-initialization: if an object of type T
can be copy-initialized with expressionE
, then E
is implicitly convertible to T
.
The equals sign, =
, in copy-initialization of a named variable is not related to the assignment operator. Assignment operator overloads have no effect on copy-initialization.
1 #include2 #include 3 #include 4 5 int main() 6 { 7 std::string s = "test"; // OK: constructor is non-explicit 8 std::string s2 = std::move(s); // this copy-initialization performs a move 9 10 // std::unique_ptr p = new int(1); // error: constructor is explicit11 std::unique_ptr p(new int(1)); // OK: direct-initialization12 13 int n = 3.14; // floating-integral conversion14 const int b = n; // const doesn't matter15 int c = b; // ...either way16 }
See also