I found by accident that the following compiles:
#include <string>
#include <iostream>
class A{
int i{};
std::string s{};
public:
A(int _i, const std::string& _s) : i(_i), s(_s) {
puts("Called A(int, const std::string)");
}
};
A foo(int k, const char* cstr){
return {k, cstr}; // (*)
}
int main(){
auto a = foo(10, "Hi!");
return 0;
}
The line of interest is (*). I guess the function foo
is equivalent to:
A foo(int k, const char* str){
return A(k, cstr);
}
However, is there a special name for this mechanism in (*)? Or is it just the simple fact that the compiler knows which constructor to call due to the return type?
return Expression? Return expressions are denoted with the keyword return . Evaluating a return expression moves its argument into the designated output location for the current function call, destroys the current function activation frame, and transfers control to the caller frame.
return statement syntax return ( expression ) ; A value-returning function should include a return statement, containing an expression. If an expression is not given on a return statement in a function declared with a non- void return type, the compiler issues a warning message.
When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x , where x is a number.
In programming, return is a statement that instructs a program to leave the subroutine and go back to the return address. The return address is located where the subroutine was called.
return {k, cstr};
means that {k, cstr}
is the initializer for the return value. Also, it indicates "return an object of the function's return type initialized with k
and cstr
, which means that the exact behavior depends on the returned object's type".
The return value can be initialized in two different ways:
return A(k, cstr);
- the return value is copy-initialized from k, cstr
return {k, cstr};
- the return value is copy list initialized from the class A
.This is a specific form of copy list initialization
See number 8 on the list in that reference:
List initialization is performed in the following situations:
...
copy-list-initialization (both explicit and non-explicit constructors are considered, but only non-explicit constructors may be called)
...
- in a return statement with braced-init-list used as the return expression and list-initialization initializes the returned object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With