Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between return {} and return Object{}

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}; }
like image 683
Elvis Dukaj Avatar asked Jun 21 '18 15:06

Elvis Dukaj


People also ask

What is difference between return and return value in java?

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.

What is the difference between return and return value?

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.

What is difference between return and return in Javascript?

First function returns an empty string, second returns nothing ie undefined .

What is int a {} in C++?

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.


1 Answers

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)

like image 158
songyuanyao Avatar answered Oct 01 '22 19:10

songyuanyao