return{}的含义 - C++11新特性

  之前有小伙伴在刷题过程中,遇到 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>并将这个对象返回
}
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ac君

在你们的鼓励下我会多多分享代码

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值