聚合初始化中出现异常

Exception in aggregate initialization

本文关键字:异常 初始化      更新时间:2023-10-16

在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()});
}

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

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

我做错了什么?

向致以最良好的问候

这是gcc错误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 (...) {}
}

此打印:

create

它应该打印(正确地说,就像叮当声一样(:

create
destroy    

您没有关联的try/catch,因此程序终止。

在这种情况下不需要堆叠展开。

以下内容应能解决您可能出现的泄漏。

int main()
{
try
{
std::make_unique<C>(C{makeB(), makeListAWithException()});
}
catch (...)
{
}
}

如果你改成下面的样子,我认为问题已经解决了

std::make_unique<C>(C{makeB(),makeListAWithException()});

auto b = makeB();
std::make_unique<C>(C{b,makeListAWithException()});