c++ - 为什么 C++ 从推断的返回类型中剥离引用限定符,为什么生命周期扩展不起作用?

标签 c++

给定以下代码:

template <typename U> U func1(std::function<U()> func2) {
  return func2();
}

const int x = 1;
const int& result1 = func1<const int&>([&x]() { return x; });
// result1 = ??????? (random garbage)
const int& result2 = [&x]() { return x; }();
// result2 = 1

在推断返回值时,默认情况下 lambda 从 x 的类型中去除引用限定符似乎相当不方便,在这种情况下偷偷地导致对已破坏的临时对象的引用。为什么要以这种方式设计此语言功能?

为什么 result2 可以工作,而 result1 不能延长临时的生命周期?

最佳答案

template <typename U>
U func1(std::function<U()> func2) {
  return func2();
}

当您使用 U = const int& 实例化此模板时,您将获得:

const int& func1(std::function<const int&()> func2) {
  return func2();
}

然后,你传递一个 lambda [&x](){ return x; }func1

事情是这样的:根据 8.1.5.4 Lambda 表达式,lambda 的返回类型推导为 int:

If a lambda-expression does not include a lambda-declarator, it is as if the lambda-declarator were (). The lambda return type is auto, which is replaced by the type specified by the trailing-return-type if provided and/or deduced from return statements as described in 10.1.7.4.

意思是上面的func2返回的是一个临时的

根据 15.2.6.2 临时对象:

The lifetime of a temporary bound to the returned value in a function return statement (9.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.

所以foo1的返回值绑定(bind)到临时销毁一次

return func2();

完成。

result2 的情况下,lambda 仍然返回一个临时的 int,但是临时的生命周期延长到 result2 的生命周期根据 15.2.6 临时对象,因为这种情况不属于标准本节中列出的任何异常(exception)情况。

关于c++ - 为什么 C++ 从推断的返回类型中剥离引用限定符,为什么生命周期扩展不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48102809/

相关文章:

c++ - 通过引用成员函数传递成员变量(QList)?

c++ - 我可以将 RetroArch 移植到 Native Client 吗

c++ - 将顶点坐标转换为 "same"屏幕坐标

c++ - GStreamer Win x64——是否缺少 dshowvideosrc?

c++ - C++ 命名空间中的内联函数

c++ - 为什么显式构造被视为(隐式)缩小转换?

c++ - 为什么另一个进程不能访问内存位置?

c++ - DECLARE_DYNAMIC 和 DECLARE_DYNCREATE 之间的区别?

c++ - Jsoncpp 错误地写入浮点值

c++ - 将函数添加到先前链接的文件后出现多定义链接器错误