簡體   English   中英

此函數和lambda有什么區別?

[英]What's the difference between this function and the lambda?

#include<iostream>

using namespace std;

int* New()
{
    return new int(666);
}
int Foo()
{
    //method1:
    int* it = New();
    return *it;
    //method2:
    return []() { return *(new int(666)); };//Complier has a complain here
    /*Both New() and Lambda are callable object, are there any differences between method1 and method2?*/ 
}
int main()
{
    cout << Foo() << endl;
    return 0;
}

我剛接觸C ++,遇到上面的情況,我曾回顧過C ++ Primer的10.3.2至10.3.3章,其中介紹了lambda表達式,但它對我不起作用,我對此也感到困惑我列出的最后一個注釋。

return []() { return *(new int(666)); };

該行試圖返回lambda本身。 您要調用 lambda並返回它產生的整數:

return []() { return *(new int(666)); }();  // Note the () at the end

不過,定義lambda函數僅立即調用並沒有多大意義。 當您需要實際返回一個函數或將一個作為參數時,它們會更常用。 (不過,這是一項更高級的操作,因此您現在不應該擔心它。)


單獨說明:您的程序使用new分配整數,但從未使用delete釋放它們。 這是內存泄漏 ,您應該避免這種情況。

實際上,我沒有調用我的lambda,因為它缺少調用運算符。 因此,我將其修復為:

return []() { return *(new int(666)); }();

現在可以使用了。

我回顧了C ++ Primer的10.3.2章中的詞:“我們調用lambda的方式與使用調用運算符調用函數的方式相同”。

暫無
暫無

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

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