c++ - 聚合初始化异常

标签 c++ exception c++14 aggregate valgrind

在 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/

相关文章:

c++ - 正确使用 Boost 库需要哪些先验知识?

java - 你如何记录未经检查的异常?

c++ - 在通用 lambda 中使用模板参数

c++ - 为什么 "auto ch = unsigned char{' p'}"在 C++ 17 下不能编译?

c++ - 表达式模板未完全内联

C++ 连接两个数组而不进行深度复制

java - 返回一个值并抛出异常?

java - 在java中打开文件给出异常

c++ - 右值引用限定符是否应该返回右值引用?

javascript - 为什么 Node JS 中需要 LIBUV?