在 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 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 (...) {} }
这打印:
create
它应该打印(如 clang,正确地那样):
create
destroy
关于c++ - 聚合初始化异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51259876/