简体   繁体   中英

Initializing a variable with function-style cast in C++

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 ? ie 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

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

Your analysis is missing some steps.

 int *c = new int(a);
  1. This performs direct initialization of a dynamically-allocated int instance.

  2. The new operator evaluates to a pointer prvalue (type = int* ) which is the address of this new int object.

  3. c is copy-initialized from the pointer prvalue.

 int d = int(a);
  1. This performs direct initialization of a temporary int instance, which is a prvalue (type = int ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM