聚合初始化中出现异常
Exception in aggregate initialization
在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()});
相关文章:
- 对象初始化后在C++中显示 char 数组时的异常行为
- c++ 中的异常类何时初始化?
- 未找到匹配的运算符删除;如果初始化引发异常,内存将不会被释放
- 当使用lambda进行变量的复杂初始化时,如何处理从内部抛出的lambda外部异常
- 聚合初始化中出现异常
- 在类声明中初始化 const 成员变量时在调试模式下出现异常
- 初始化引发异常的对象
- 异常 尝试初始化动态数组时未处理
- 为什么初始化构造函数列表参数时会发生异常?
- 视觉C++ Int 似乎没有初始化并引发异常:读取访问冲突
- 如果初始化或销毁因未处理的异常而终止,则必须销毁完全构造的子对象
- 初始化不正确的价值不良样式后,正在抛出异常
- 如果从 c++ 中的构造函数引发异常,如何清理初始化的资源
- DLL 中的 C++ 静态局部变量初始化会导致_CrtIsValidHeapPointer异常
- 变量 C++ 的异常初始化
- std::互斥初始化异常
- 出现异常后重试本地静态变量初始化
- 类型初始化使用 OpenSsl.net 异常
- 每当我尝试初始化Employer对象时,我的程序都会给出一个未处理的异常错误
- TheoraVideoManager不会在0x7329E13D(msvcr110.dll)处初始化未处理的异常