Why can std::function be constructed with a lambda with a different return type?

不羁的心 提交于 2019-12-08 17:05:27

问题


The following compiles fine:

#include <functional>

int main()
{
    std::function<const int&()> f = []() -> int {return 1;};
    const int& r = f(); // r is a dangling reference
    return 0;
}

How come it's possible to set an std::function with a const int& return type to a lambda with an int return type? Allowing this sort of cast to happen implicitly and with no warning is a gotcha IMHO.


回答1:


You can construct a std::function with any object which is callable with the relevant arguments and whose return value is implicitly convertible to the std::function return. int is implicitly convertible to const int&, so the rules are met.

A compiler could feel free to warn about this, but it seems like a lot of work for a particularly corner-y corner case.



来源:https://stackoverflow.com/questions/41549632/why-can-stdfunction-be-constructed-with-a-lambda-with-a-different-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!