聚合初始化中的异常

Lat*_*eef 5 c++ valgrind aggregate exception c++14

在C++ 14(gcc 6.3)中,我有以下代码:

#include <memory>
#include <vector>
#include <stdexcept>

struct A
{
    int a1;
    int a2;
};

struct B
{
    int b1;
    std::shared_ptr< std::vector<A> > Alist;        
};

struct C
{
    std::shared_ptr<B> b;
    std::shared_ptr< std::vector<A> > Alist;        
};    

std::shared_ptr< std::vector<A> > makeListA()
{
    std::vector<A> toto = {{0,1}, {2,3}};
    return std::make_shared< std::vector<A> >(toto);
}

std::shared_ptr< std::vector<A> > makeListAWithException()
{
    throw std::out_of_range("My exception");
}

std::shared_ptr<B> makeB()
{
    return std::make_shared<B>(B{0, makeListA()});
}

main()
{
    std::make_unique<C>(C{makeB(),makeListAWithException()});
}
Run Code Online (Sandbox Code Playgroud)

当运行valgrind时,我有一个内存泄漏:它看起来像"makeB()"函数创建的对象没有被释放.我只有在使用花括号的聚合初始化时才遇到这个问题.

当我在每个类(A,B和C)上定义显式构造函数时,我没有这个问题.

我究竟做错了什么 ?

最好的祝福

Bar*_*rry 5

这是gcc bug 66139.这是一个简短的复制,由Andrzej提供(博客文章中有更详尽的描述):

#include <cstdio>
#include <stdexcept>

struct Resource
{
  explicit Resource(int) { std::puts("create"); }
  Resource(Resource const&) { std::puts("create"); }
  ~Resource() { std::puts("destroy"); }
};

Resource make_1() { return Resource(1); }
Resource make_2() { throw std::runtime_error("failed"); }

struct User 
{
  Resource r1;
  Resource r2;
};

void process (User) {}

int main()
{
  try {
    process({make_1(), make_2()});
  }
  catch (...) {}
}
Run Code Online (Sandbox Code Playgroud)

这打印:

create
Run Code Online (Sandbox Code Playgroud)

它应该打印(作为clang,正确,确实):

create
destroy    
Run Code Online (Sandbox Code Playgroud)