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

下面这段代码在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?

大家讲道理
大家讲道理

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

reply all(3)
洪涛

What is the return value when decompression fails? lambda Support feels like there should be no problem with this. gcc 4.5 has started to support lambda. gcc 4.8.5 is already a relatively stable version. The compiler's bug should be the last thing to consider...

伊谢尔伦

When the guard object is destructed, it will call
[&](){if (dstBuf) delete[] dstBuf; dstBuf=NULL;}
The decompression failure you mentioned here means that the uncompress function return is not Z_OK like this? Or is there another problem with the program?

Also, [&]()mutable -->void {if (dstBuf) delete[] dstBuf; dstBuf=NULL;} this can be modified dstBuf. I haven't tested this, so I don't know if it is true.

迷茫

Regarding the implementation of ScopeGuard, you can refer to Andrei Alexandrescu’s implementation in Facebook’s open source folly library

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!