Search code examples
c++c++11initializationlist-initialization

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}; }

Solution

  • 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)