Is there any significant difference between this two functions?
struct Object {
Object(int i) : i{i}
{
}
int i;
};
Object f() { return {1}; }
Object g() { return Object{1}; }
Returning a Value from a Method In Java, every method is declared with a return type such as int, float, double, string, etc. These return types required a return statement at the end of the method. A return keyword is used for returning the resulted value. The void return type doesn't require any return statement.
Return by value is like the artist handing you a printed copy of the boat they drew. Return by reference is like the artist telling you the address of the house they left your picture in.
First function returns an empty string, second returns nothing ie undefined .
C++ int. The int keyword is used to indicate integers. Its size is usually 4 bytes. Meaning, it can store values from -2147483648 to 2147483647.
The 1st one is copy-list-initialization, the approriate constructor (i.e. Object::Object(int)
) will be selected to construct the return value.
The 2nd one will construct a temporary Object
by direct-list-initialization, (which also calls Object::Object(int)
), then copy it to the return value. Because of copy elision (which is guaranteed from C++17), the copy- or move- construction is omitted here.
So for your example they have the same effect; Object::Object(int)
is used to construct the return value. Note that for the 1st case, if the constructor is explicit
then it won't be used.
direct-list-initialization (both explicit and non-explicit constructors are considered)
copy-list-initialization (both explicit and non-explicit constructors are considered, but only non-explicit constructors may be called)
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