This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug c++/80664] New: Destructor not called upon exception while initializing a vector
- From: "akrzemi1 at gmail dot com" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: Mon, 08 May 2017 09:02:47 +0000
- Subject: [Bug c++/80664] New: Destructor not called upon exception while initializing a vector
- Auto-submitted: auto-generated
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80664
Bug ID: 80664
Summary: Destructor not called upon exception while
initializing a vector
Product: gcc
Version: 8.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: akrzemi1 at gmail dot com
Target Milestone: ---
The following program logs calls to successful constructors and destructors of
class `R`. I expect the number of constructions to equal the number of
destructions. But when second construction fails, the destructor of the
previously fully created object is not called. This is becayse shared_ptr's
destructor is skipped! This happens when list-initializing a vector of
shared_ptr's:
```
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <vector>
void acquire_resource() // emulates failure to acquire the second resource
{
static int resources_exhausted = 0;
if (resources_exhausted)
throw std::runtime_error("failed");
else
++resources_exhausted;
}
struct R
{
explicit R(int)
{
acquire_resource();
std::puts("create");
}
R(R const&) = delete; // no copying, no moving
~R() { std::puts("destroy"); }
};
int main()
{
try {
std::vector<std::shared_ptr<R>> v {
std::make_shared<R>(1), // created, but never destroyed
std::make_shared<R>(2) // creation fails for this one
};
}
catch (...) {}
}
```
I consider the bug serious as it undermines the trust in C++'s "RAII
philosophy".