“返回{}"是什么意思?语句在 C++11 中是什么意思?

声明是什么

return {};

在 C++11 中指明,以及何时使用它来代替(说)

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

return NULL;

return nullptr;

推荐答案

return {};表示返回一个用空list-initializer".确切的行为取决于返回对象的类型.

return {}; indicates "return an object of the function's return type initialized with an empty list-initializer". The exact behaviour depends on the returned object's type.

来自 cppreference.com (因为 OP 标记为 C++11,我排除了C++14 和 C++17 中的规则;详情请参阅链接):

From cppreference.com (because the OP is tagged C++11, I excluded the rules in C++14 and C++17; refer to the link for further details):

  • 如果括号初始化列表为空且 T 是具有默认构造函数的类类型,则执行值初始化.
  • 否则,如果 T 是聚合类型,则执行聚合初始化.
  • 否则,如果 T 是 std::initializer_list 的特化,则根据上下文,从花括号初始化列表中直接初始化或复制初始化 T 对象.
  • 否则,将分两个阶段考虑 T 的构造函数:

  • If the braced-init-list is empty and T is a class type with a default constructor, value-initialization is performed.
  • Otherwise, if T is an aggregate type, aggregate initialization is performed.
  • Otherwise, if T is a specialization of std::initializer_list, the T object is direct-initialized or copy-initialized, depending on context, from the braced-init-list.
  • Otherwise, the constructors of T are considered, in two phases:

  • 检查所有将 std::initializer_list 作为唯一参数或作为第一个参数(如果其余参数具有默认值)的构造函数,并通过重载决议与 std::initializer_list 类型的单个参数进行匹配
  • 如果前一阶段没有产生匹配,则 T 的所有构造函数都参与重载决议,以针对由括号初始化列表的元素组成的参数集,并限制只允许非缩小转换.如果此阶段生成一个显式构造函数作为复制列表初始化的最佳匹配,则编译失败(注意,在简单的复制初始化中,根本不考虑显式构造函数).

否则(如果 T 不是类类型),如果括号初始化列表只有一个元素并且 T 不是引用类型或者是与类型兼容的引用类型元素, T 是直接初始化(在直接列表初始化中)或复制初始化(在复制列表初始化中),但不允许缩小转换.

Otherwise (if T is not a class type), if the braced-init-list has only one element and either T isn't a reference type or is a reference type that is compatible with the type of the element, T is direct-initialized (in direct-list-initialization) or copy-initialized (in copy-list-initialization), except that narrowing conversions are not allowed.

在 C++11 之前,对于返回 std::string 的函数,您应该这样写:

Before C++11, for a function returning a std::string, you would have written:

std::string get_string() {
    return std::string();
}

使用C++11中的大括号语法,不需要重复类型:

Using the brace syntax in C++11, you don't need to repeat the type:

std::string get_string() {
    return {}; // an empty string is returned
}

return NULLreturn nullptr 应该在函数返回指针类型时使用:

return NULL and return nullptr should be used when the function returns a pointer type:

any_type* get_pointer() {
    return nullptr;
}

但是,NULL 自 C++11 起已弃用,因为它只是整数值 (0) 的别名,而 nullptr 是真正的指针类型:

However, NULL is deprecated since C++11 because it is just an alias to an integer value (0), while nullptr is a real pointer type:

int get_int() {
    return NULL; // will compile, NULL is an integer
}

int get_int() {
    return nullptr; // error: nullptr is not an integer
}

相关文章