Untitled conversation
- User
double foo () { return 3; }does it perform internal implicit conversion after returning 3 to construct double? does it perform copy initialization(with copy elision)?
- Assistant
double foo () {
return 3;
}
does it perform internal implicit conversion after returning 3 to construct double? does it perform copy initialization(with copy elision)?
Yes, both behaviors you've described occur in the provided C++ code. Let's break them down:
In the function:
double foo () {
return 3;
}
3 is of type int. Since the function foo is declared to return a double, the integer 3 is implicitly converted to a double (3.0) during the return statement. This is a standard type conversion in C++ where an int can be implicitly converted to a double without any explicit casting.Copy Initialization: When you return a value from a function, C++ typically performs copy initialization. This involves creating a temporary object from the returned expression and then copying (or moving) it to the location where the return value is expected. In the case of double, this would conceptually involve initializing a double with the value 3.0.
Copy Elision (Optimization): Modern C++ compilers are very good at optimizing away unnecessary copies through a mechanism known as copy elision. Specifically:
Return Value Optimization (RVO): The compiler can construct the return value directly in the memory location where it would ultimately reside, eliminating the need for a separate temporary object and thus avoiding the copy.
Mandatory Copy Elision (C++17 and Later): Starting with C++17, certain cases of copy elision are mandatory, meaning the compiler must eliminate the copy, even if the copy constructor has side effects. However, for simple types like double, copy elision has been effectively optimized for a long time.
In your specific example with double, which is a trivially copyable type, the compiler will likely optimize the return such that no actual copy occurs. The value 3.0 is directly used as the return value without any intermediate copying steps.
Implicit Conversion: Yes, the integer 3 is implicitly converted to a double (3.0) when returning from the function.
Copy Initialization with Copy Elision: Conceptually, copy initialization is used, but due to copy elision optimizations, especially in modern C++ standards, no actual copy operation is performed for such simple types.
double foo () {
// Implicitly converts int 3 to double 3.0
// Copy initialization is conceptually used, but copy elision optimizes it away
return 3;
}
Feel free to ask if you have more questions regarding C++ behaviors or other programming concepts!
Not yet included in a published release.