在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)上定义显式构造函数时,我没有这个问题.
我究竟做错了什么 ?
最好的祝福