簡體   English   中英

為什么這個 std::function 和運算符會導致分段錯誤?

[英]Why does this std::function and operator cause a segmentation fault?

我沒有發現此代碼有任何問題,但它給了我一個段錯誤。 將 std::function 更改為正常的 function 即可解決問題。 同樣刪除重載運算符中的加法也解決了這個問題。 還將 Point 構造函數從 const int& 更改為 int 也解決了這個問題。 但我不明白為什么。 https://onlinegdb.com/Sy32UTllO

#include <iostream>
#include <functional>

struct Point
{
    int x, y;
    Point() {}
    Point(const int& x, const int& y) {}
};
Point operator+(const Point& p1, const Point& p2) { return {p1.x+p2.x, p1.y+p2.y}; }
Point p1, p2;
std::function<const Point&()> fn = []{ return p1; };

int main()
{
    Point p3 = fn() + p2;
    return 0;
}
std::function<const Point&()> fn = []{ return p1; };

因為你沒有指定lambda的返回值,所以默認按值返回。 所以fn試圖返回對臨時對象的引用,這是未定義的行為。

改為這樣做:

std::function<const Point&()> fn = []() -> const Point& { return p1; };

[]{ return p1; } []{ return p1; }按值返回,因此fn()返回一個懸空引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM