# nvc++: when a constructor throws, its virtual bases are destroyed multiple times, at wrong bases

Summary

When an exception leaves the body of a constructor of a class whose virtual bases are inherited through its base classes, nvc++'s cleanup code destroys each virtual base once more for every direct base class that inherits it: twice through a single base, three times through two. Each extra destruction happens at the address the virtual base would have in a standalone object of that base class, which inside the actual, larger object holds unrelated data. [except.ctor]/3 requires each fully constructed base sub-object to be destroyed exactly once. In real code this corrupts the heap and aborts the program, even when the caller catches the exception.

Reproduced with

  • nvc++ 25.11-0
  • nvc++ 26.9-0 (EDG 6.8), x86-64 Linux (-tp sapphirerapids, Ubuntu 24.04)

Other nvc++ versions may well be affected too. These two behave identically. It reproduces at -O0, -O1, -O2, -O3 and -fast -O3. No option we tried avoids it (about 30, among them --gnu_version=130300, --zc_eh, -Meh_frame, --no_rtti, -Kieee, -Mnovect, and -std=c++11 through c++23). g++ 13 and 14 and clang 20 compile the same source correctly, at every -O level.

Reproducer

The program counts each destruction of the virtual base VB2 and records where it ran. It reports a violation instead of crashing, and exits 1 when the compiler does not conform.

/*
 * [except.ctor]/3: when a constructor exits by an exception, the destructor
 * of each fully constructed base sub-object runs exactly once. Here class C's
 * constructor throws, and its virtual base VB2 must be destroyed once, at
 * the address, where it was constructed. VB2 owns no heap memory, so a second
 * destruction, or one at the wrong address, is counted and reported rather
 * than crashing the program. Exit status: 0 conforming, 1 not.
 */
#include <cstddef>
#include <cstdio>
#include <stdexcept>
#include <vector>

static int ctorVB, dtorVB;
static const void *builtAt;		/* where VB2 was constructed */
static const void *destroyedAt[4];	/* where each ~VB2 ran */
static int throwLine;

struct VB1 {
	long a_ = 1, b_ = 2, c_ = 3;

	virtual ~VB1() = default;
};

struct VB2 {
	long pad_[4] = { 0, 1, 2, 3 };

	VB2()
	{
		++ctorVB;
		builtAt = this;
	}

	virtual ~VB2()
	{
		if (dtorVB < 4)
			destroyedAt[dtorVB] = this;
		++dtorVB;
	}

	virtual void update() = 0;
};

struct Mid : public virtual VB1, public virtual VB2 {
	void
	update() override
	{
	}
};

struct A : public Mid {
	double x_ = 0;
};

struct B : public A {
	std::vector<double> v1_, v2_;

	explicit B(int n) : v1_(n), v2_(n)
	{
	}
};

struct C : public B {
	std::vector<double> e1_, e2_, e3_, e4_, e5_;
	double n_;

	explicit C(double n)
	    : B(2), e1_(3), e2_(3), e3_(3), e4_(3), e5_(3), n_(n)
	{
		if (n_ < 0) {
			throwLine = __LINE__;
			throw std::runtime_error("boom");
		}
	}
};

int
main()
{
	bool ok;
	int i;

	try {
		C c(-1.0);
	} catch (const std::exception &) {
	}
	ok = ctorVB == 1 && dtorVB == 1 && destroyedAt[0] == builtAt;
	if (ok) {
		std::printf("%s:%d: CONFORMING: VB2 constructed once, "
		    "destroyed once where it was built\n", __FILE__, throwLine);
		return (0);
	}
	std::printf("%s:%d: NON-CONFORMING: after this constructor threw, "
	    "VB2 (constructed %d time(s)) was destroyed %d time(s), at",
	    __FILE__, throwLine, ctorVB, dtorVB);
	for (i = 0; i < dtorVB && i < 4; i++)
		std::printf(" %+td", (const char *)destroyedAt[i] -
		    (const char *)builtAt);
	std::printf(" bytes from where it was built\n");
	return (1);
}
$ nvc++ -std=c++17 -O2 ctor-virtual-base-dtor.cpp -o t && ./t; echo "exit $?"
ctor-virtual-base-dtor.cpp:31: NON-CONFORMING: after this constructor threw, VB2 (constructed 1 time(s)) was destroyed 2 time(s), at -128 +0 bytes from where it was built
exit 1

$ g++ -std=c++17 -O2 ctor-virtual-base-dtor.cpp -o t && ./t; echo "exit $?"
ctor-virtual-base-dtor.cpp:31: CONFORMING: VB2 constructed once, destroyed once where it was built
exit 0

$ clang++-20 -std=c++17 -O2 ctor-virtual-base-dtor.cpp -o t && ./t; echo "exit $?"
ctor-virtual-base-dtor.cpp:31: CONFORMING: VB2 constructed once, destroyed once where it was built
exit 0

The -128 is the virtual base’s position in a standalone B, 0x80 bytes short of its position in a C. If VB2 owns heap memory itself (for example a std::vector member), the first misplaced destruction frees whatever pointer lies at that wrong address, and the program aborts: free(): invalid pointer.

More than one base class

ctor-virtual-base-count.cpp (attached, same instrumentation) throws from three shapes of hierarchy and counts the destructions of the virtual base VB:

shape (constructor that throws)              nvc++ 25.11, 26.9      g++ 13, clang 20
D -> C -> B -> A -> virtual VB               2, at -48 +0           1, at +0
C -> B1, B2;  B1, B2 -> virtual VB           3, at -48 -80 +0       1, at +0
C -> B1, B2, B3;  each -> virtual VB         4, at -48 -80 -112 +0  1, at +0

The same at -O0 and -O2. Depth adds nothing: only the cleanup of the class whose constructor throws calls its bases’ complete-object destructors, one for each direct base class, each destroying the shared virtual base at that base class’s own layout.

Cause

A class with virtual bases has two destructors:

Both are defined by the C++ ABI that g++, clang and nvc++ follow on Linux, the “Itanium C++ ABI” (named after the processor it was first written for: 1.1 Definitions, and the mangled names in 5.1.4.3 Constructors and Destructors).

Each constructor is likewise emitted twice. The complete-object constructor of C (_ZN1CC1Ed) builds the virtual bases VB1 and VB2, then calls the base-object constructor (_ZN1CC2Ed), which builds B and C’s own members. When that body throws, the base-object constructor’s cleanup must destroy B with its base-object destructor; the complete-object constructor’s cleanup then destroys the virtual bases, once.

nvc++ instead destroys the virtual bases from inside the base-object constructor’s cleanup as well. The destructors each cleanup calls at -O0 (nvc++ 25.11 and 26.9 identical):

          _ZN1CC2Ed (base-object ctor)        _ZN1CC1Ed (complete-object ctor)
nvc++     _ZN1BD1Ev: B's complete-object      _ZN3VB1D1Ev _ZN3VB2D1Ev
          destructor, virtual bases included
g++ and   (not emitted: their _ZN1CC1Ed is    _ZN1BD2Ev _ZN3VB1D2Ev _ZN3VB2D2Ev,
clang     a complete copy of the body)        each once

At -O2 and above nvc++ inlines the virtual bases’ destructors, so fewer calls are visible, but the program reports the same two destructions. Which destructor a cleanup calls is decided when the front end generates code, before any optimisation; the defect is present at -O0 already.

B’s complete-object destructor locates the virtual bases by B’s own layout, which is why the first destruction runs 0x80 bytes short of the real VB2. The complete-object constructor’s cleanup then destroys them a second time, at the correct address.

Impact

This pattern is the core of QuantLib: LazyObject derives virtually from Observable and Observer, so every instrument, term structure, index and cash flow has this hierarchy, and Observable owns heap memory. Any of their constructors that rejects its arguments with an exception, as QuantLib’s do throughout, crashes the process. A catch around the construction does not help: the damage is done during unwinding, before the handler is reached.

  • QuantLib’s test suite: 10 aborts (“memory access violation”) with nvc++, none with g++.
  • In production, a risk run over a large bond portfolio died on one business date: two bonds’ schedules ended in an overnight-indexed coupon period without a business day. The coupon’s constructor rightly rejects that, but the throw killed the whole run instead of failing those two bonds.

Our workaround is to move each such validation out of the constructor body into the base-class initialiser, before any sub-object exists. That does not scale to a library of this size.

Expected

The base-object constructor’s cleanup destroys B with its base-object destructor, and the virtual bases are destroyed once, by the complete-object constructor’s cleanup, at the addresses they were built at, as g++ and clang do.

ctor-virtual-base-count.cpp.txt (2.7 KB)

Hi UnitedMarupials and thanks for the report!

I was able to reproduce the issue here and have filed a report, TPR #39153. We’ll have engineering investigate.

-Mat