Reputation: 2886
int main(){
int a = 5; // copy initialization.
int b(a); // direct initialization.
int *c = new int(a); // also direct initialization, on heap.
int d = int(a); // functional cast, also direct initialization?
// or copy initialization?
return 0;
}
I have 2 questions on this:
1 - It's not clear to me if int(a);
is only a cast, or if it's also an initializer.
Is d
being copy initialized
or is it being direct initialized
?
i.e is the expression equal to this:
int d = 5;
or this
int d(5);
2- I want to confirm if new int(a);
is only an initializer and not a cast to int. Also want to confirm if it's direct initialization
and not copy initialization
.
I have read section (3) of the reference but the answer is not clear to me: https://en.cppreference.com/w/cpp/language/direct_initialization
- initialization of a prvalue temporary (until C++17)the result object of a prvalue (since C++17) by functional cast or with a parenthesized expression list
Upvotes: 2
Views: 602
Reputation: 283733
Your analysis is missing some steps.
int *c = new int(a);
This performs direct initialization of a dynamically-allocated int
instance.
The new
operator evaluates to a pointer prvalue (type = int*
) which is the address of this new int
object.
c
is copy-initialized from the pointer prvalue.
int d = int(a);
This performs direct initialization of a temporary int
instance, which is a prvalue (type = int
).
d
is copy-initialized from this prvalue.
In both cases, the copy constructor call is eligible for elision in all C++ versions, and elision is guaranteed in the latest Standard.
Upvotes: 4