c++ lambda表达式问题
大家讲道理
大家讲道理 2017-04-17 13:46:50
0
3
363

下面这段代码在ubuntu g++ 4.6.3 可以正常运行,在g++ 5.2 中运行正常。但是在centos g++ 4.8.5中运行失败,但是把lambda表达式注释之后就可以正常运行,这个和编译器有关吗?

// 这是一个工具类
class ScopeGuard
{
public:
    explicit ScopeGuard(std::function<void ()> onExitScope)
    :onExitScope_(onExitScope)
    {

    }

    ~ScopeGuard()
    {
        onExitScope_();
    }
private:
    std::function<void ()> onExitScope_;
};

下面程序是用来解压的程序,但是在centos中会解压失败。

    // 上面还有类似的几个lambda表达式
    int dstLen = 10 * 1024 * 1024;
    char *dstBuf = new char[dstLen];
        // 把下面一行注释掉就可以正确解压,只要函数内有一个这样的表达式就会解压失败
    ScopeGuard guard([&](){if (dstBuf) delete[] dstBuf; dstBuf=NULL;});

        // src 是解压前的数据,fileLen是数据长度
    int err = uncompress((Bytef *)dstBuf, (uLongf*)&dstLen, (Bytef*)src, fileLen);

    if (err != Z_OK)
    {
        cout<<"uncompress error..."<<err<<endl;
        return false;
    }

请问,是我的lambda方式用错了还是编译器的bug?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回覆(3)
洪涛

解壓縮失敗的回傳值是啥? lambda支援感覺這個應該沒問題,gcc 4.5開始支援lambdagcc 4.8.5已經算是比較穩定的版本了,編譯器的bug應該是最後考慮的事情...

伊谢尔伦

在guard物件析構的時候會呼叫
[&](){if (dstBuf) delete[] dstBuf; dstBuf=NULL;}
你這裡說的解壓縮失敗,是指uncompress函數回傳不是Z_OK這樣嗎?還是說程式會出別的問題?

還有就是[&]()mutable -->void {if (dstBuf) delete[] dstBuf; dstBuf=NULL;}這樣才能修改dstBuf吧。這個我沒有做測試,不知道是不是。

迷茫

關於ScopeGuard的實現,你可以參考 Andrei Alexandrescu在facebook開源的folly庫中的實現

https://github.com/facebook/folly/blob/master/folly/ScopeGuard.h

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!