之前有小伙伴在刷题过程中,遇到 return{} 懵逼了,其实这个是C++11的新特性,本文将介绍return{}的用法,如果有不足欢迎大佬斧正(>人<;)~
我们先来看看比较官方的details
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:
- All constructors that take std::initializer_list as the only
argument, or as the first argument if the remaining arguments have
default values, are examined, and matched by overload resolution
against a single argument of type std::initializer_list
- If the previous stage does not produce a match, all constructors of T
participate in overload resolution against the set of arguments that
consists of the elements of the braced-init-list, with the restriction
that only non-narrowing conversions are allowed. If this stage
produces an explicit constructor as the best match for a
copy-list-initialization, compilation fails (note, in simple
copy-initialization, explicit constructors are not considered at all).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.Otherwise, if T is a reference type that isn’t compatible with the type of the element. (this fails if the reference is a non-const
lvalue reference)Otherwise, if the braced-init-list has no elements, T is value-initialized.
看了解释后,归结就是 “返回用大括弧初始化的该函数对象(返回的类型和函数类型一样)” 举个例子后就能明白了
在C++11之前, 你想返回一个string的函数,你可能会这样写:
string get_string() {
return string();
}
在C++11之后,可以这样写:
std::string get_string() {
return {}; // 即返回这个函数所构造出来的对象
}
这里再举个例子:
vector<int> twoSum(vector<int>& nums, int target) {
//...经过一系列操作后构造好了nums这个vector数组
if(target > 10) return {}; //返回一个空的vector<int>对象
else if(target < 5) return nums; //直接返回nums作为对象
else return {1, 2, 3}; //直接构造好vector<int>并将这个对象返回
}