小编Eri*_*ric的帖子

在std :: list <shared_ptr>的C++ 14初始化列表中间抛出GCC(但不是Clang)下的内存泄漏

考虑以下程序:

#include <stdexcept>
#include <stdio.h>
#include <memory>
#include <list>
class Foo {
public:
    Foo(){
        if (s_ct==0) {throw std::bad_alloc();}
        --s_ct;
        fprintf(stderr, "ctor %p\n", this);
    }
    ~Foo(){
        fprintf(stderr, "dtor %p\n", this);
    }
private:
    static int s_ct;
};

int Foo::s_ct = 2;

int main(){
    try {
        std::list<std::shared_ptr<Foo>> l = {
            std::make_shared<Foo>(),
            std::make_shared<Foo>(),
            std::make_shared<Foo>()
        };
    } catch (std::bad_alloc&) {
        fprintf(stderr, "caught exception.\n");
    }
    fprintf(stderr, "done.\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译如下:

[little:~] $ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, …
Run Code Online (Sandbox Code Playgroud)

c++ exception-handling shared-ptr initializer-list c++14

22
推荐指数
1
解决办法
421
查看次数