What does “return {}” statement mean in C++11?

后端 未结 4 461
广开言路
广开言路 2021-01-30 02:59

What does the statement

return {};

in C++11 indicate, and when to use it instead of (say)

return NULL;

or

4条回答
  •  有刺的猬
    2021-01-30 03:14

    return {}; means that {} is the initializer for the return value. The return value is list-initialized with an empty list.


    Here is some background on the return value, based on [stmt.return] in the C++ Standard:

    For a function that returns by value (i.e. the return type is not a reference and not void), there is a temporary object called the return value. This object is created by the return statement, and its initializers depend on what was in the return statement.

    The return value survives until the end of the full-expression in the code that called the function; if it has class type, then its destructor will run unless it has lifetime extended by the caller binding a reference directly to it.

    The return value can be initialized in two different ways:

    • return some_expression; - the return value is copy-initialized from some_expression
    • return { possibly_empty_list }; - the return value is list-initialized from the list.

    Assuming T is the function's return type, then note that return T{}; is different to return {}: in the former, a temporary T{} is created, and then the return value is copy-initialized from that temporary.

    This will fail to compile if T has no accessible copy/move-constructor, but return {}; will succeed even if those constructors are not present. Accordingly, return T{}; may show side-effects of the copy-constructor etc., although this is a copy elision context so it may not.


    Here's a brief recap of list-initialization in C++14 (N4140 [dcl.init.list]/3), where the initializer is an empty list:

    • If T is an aggregate, then each member is initialized from its brace-or-equal-initializer if it had one, otherwise as if by {} (so apply these steps recursively).
    • If T is a class type with a user-provided default constructor, that constructor is called.
    • If T is a class type with an implicitly-defined, or = defaulted default constructor, the object is zero-initialized and then the default constructor is called.
    • If T is a std::initializer_list, the return value is an empty such list.
    • Otherwise (i.e. T is a non-class type -- return types cannot be arrays), the return value is zero-initialized.

提交回复
热议问题