Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 分配std::函数<;int(int)>;to std::function<;康斯特国际酒店;(const int&;x)>;_C++_C++11 - Fatal编程技术网

C++ 分配std::函数<;int(int)>;to std::function<;康斯特国际酒店;(const int&;x)>;

C++ 分配std::函数<;int(int)>;to std::function<;康斯特国际酒店;(const int&;x)>;,c++,c++11,C++,C++11,以下代码进行编译,但在VC++2015(发行版)中生成未定义的输出,并出现运行时错误 #包括 #包括 int main() { 函数f=[](int x){return x;}; std::函数g=f; std::cout一个右值可以绑定到一个常量&。一个常量&可以转换为右值 检查这一点: int f(int x){return x;} int const& g(int const& x){ return f(x); } 类似地,对g的调用是合法的,没有错误,但是读取g(42)

以下代码进行编译,但在VC++2015(发行版)中生成未定义的输出,并出现运行时错误

#包括
#包括
int main()
{
函数f=[](int x){return x;};
std::函数g=f;

std::cout一个右值可以绑定到一个
常量&
。一个
常量&
可以转换为右值

检查这一点:

int f(int x){return x;}
int const& g(int const& x){ return f(x); }
类似地,对
g
的调用是合法的,没有错误,但是读取
g(42)
的结果是UB——参考悬挂

一个好的编译器会看到绑定到temporary的引用被返回并发出警告


function
只检查类型是否可以在之间转换;它不进行生存期分析。可能应该这样做,因为我们可以静态地检测此错误。

考虑重写等效代码以避免lambdas或
std::function

int f(int x) { return x; } 
int const& g(int const& x) { return f(x); } 

这是一个格式完美的代码,尽管如此,它仍然会返回一个对临时对象的悬空引用,从而导致未定义的行为。原始代码是vaid,原因相同:您可以隐式地将对象转换为相同类型的引用。不幸的是,在这种情况下。

使用apple clangHigh编译并执行得非常完美非常相关/可能的重复:谢谢。至少你的例子。带有
std::function
的例子没有。
int f(int x) { return x; } 
int const& g(int const& x) { return f(x); }