If I conditionally initialize a const reference to refer to either a global object or a temporary returned from a function, the compiler calls the destructor when it goes out of scope in both cases, so the global object is destroyed twice.
#include <stdio.h>
#include <string>
using namespace std;
struct S {
string name;
S(const string & n) : name(n) {
printf("%s(%s)n", __func__, name.c_str());
}
~S() {
printf("%s(%s)n", __func__, name.c_str());
}
void g() const {
printf("%s(%s)n", __func__, name.c_str());
}
};
S f() {
return S("f");
}
S s("global");
int main(int argc, char ** argv) {
(void)argc, (void)argv;
printf("%s: beginn", __func__);
for (int i=0; i<2; i++) {
const auto & z = i ? s : f();
z.g();
}
printf("%s: endn", __func__);
}
Prints this:
S(global)
main: begin
S(f)
g(f)
~S(f)
g(global)
~S(global)
main: end
~S(global)
Tested on GCC 8.5, 14.2, and whatever https://www.programiz.com/online-compiler/6YuASdDFxt7dE used.
EDIT: note that if I replace the conditional expression with just const auto & z = s;
then the compiler doesn’t attempt to call its destructor after each loop iteration. I guess there’s something about the conditional expression that breaks lifetime extension without as much as a warning?
EDIT2: Mystery solved, an extra copy was created by the copy ctor that I forgot to instrument, so destructors worked correctly. Though the code didn’t work as intended, instead of binding the reference to the global variable it bound it to a temporary copy of it, to match the other branch. Thank you everyone who helped.
6
Here is your code, modernized to use C++23 features.
This reveals what the actual problem is.
First, you should familiarize yourself with the rule of 3/5/0 (/7* will be introduced in C++26 it is not relevant at the moment – this bold claim I’ve seen on internet can’t find official confirmation if this is actually the true).
By default, the compiler silently generates default implementations for constructors and assignment operators when nothing is defined manually. Here is a quick reference to how this works, presented in a neat table:
In your original code, the implicitly generated copy constructor is being used. Specifically, your code is unintentionally generating an extra instance of S
through the copy constructor.
This occurs in the following line:
const auto& z = i ? s : f();
This is a corner case. Note that f()
returns a value, not a reference. There is a well-defined exception for this scenario called “lifetime extension of temporary objects.” Essentially, when a temporary object is assigned to a reference, its lifetime is extended to match that of the reference.
In this case, since you are using the ternary operator and z
can refer to two different scenarios:
- A simple reference to the global
s
. - A reference that prolongs the lifetime of a temporary object returned by
f()
.
The compiler must reconcile these two possibilities to have uniform behavior of z
in each iteration. The correct behavior is to use the second scenario for both cases, which means a copy of s
is created.
As alagner
point out replacing ternary operator with simpler if
hides this extra copy since two separate instances of z
are created which can have a different behavior.
It all boils down to the type the ternary operator yields. Check with type traits.
This static_assert(std::is_same_v<decltype(i ? s : f()), S>, "!");
compiles, while
that static_assert(std::is_same_v<decltype(i ? s : f()), S&>, "!");
fails to.
It might be counter-intuitive, but note that S f();
returns by value. Therefore the resulting type of the ternary expression is going to be a copy, not a reference. Indeed, the ternary operator is capable of returning a reference, but it is not required to.
You can work around this using if
instead of the ternary operator, e.g.:
if (i) {
const auto &z = s;
z.g();
} else {
const auto &z = f();
z.g();
}
This might be suboptimal (in terms of rules like DRY) due to duplicated z.g()
in both code paths, but that was just for the sake of the example. Feel free to adjust it to match your requirements.
Demo with if-else statement (and with instrumented copy constructor): https://godbolt.org/z/MGbG61x59
Another option might be to make f()
return a reference. If it suits your needs in real life is a open question. For the sake of the example, I used a static object inside f()
.
S& f() {
static S x("f");
return x;
}
Demo with S& f()
: https://godbolt.org/z/YWfTn55Gc
This is due to how C++ manages the lifetime of objects and references, particularly in the context of automatic storage duration within a loop.
The core problem isn’t that the compiler is confused or doesn’t know it’s a global. The issue lies in the scope of the const auto& z
variable within the loop. In each iteration of the loop, z
is a new reference declared within that iteration’s scope.
Why the Double Destruction?
- The reference
z
is declared within the loop’s scope. - At the end of each loop iteration, variables with automatic storage duration declared within that scope are destroyed.
- Even though
z
refers to a global object in the second iteration, the compiler treatsz
itself as a local reference and calls the destructor of the object it refers to whenz
goes out of scope.
If you intend for the reference to potentially point to a global object and want to avoid the extra destruction, you need to manage the lifetime differently.
Few approaches:
Declare the reference outside the loop:
int main(int argc, char ** argv) {
(void)argc, (void)argv;
printf("%s: beginn", __func__);
const S& z = s; // Initialize with the global initially
for (int i=0; i<2; i++) {
if (i == 0) {
const S temp = f(); // Create a temporary
z = temp; // Try to reassign - ERROR: references cannot be reseated
} else {
z.g(); // Access the global
}
}
printf("%s: endn", __func__);
}
Use a pointer:
int main(int argc, char ** argv) {
(void)argc, (void)argv;
printf("%s: beginn", __func__);
const S* pz = &s;
S temp;
for (int i=0; i<2; i++) {
if (i == 0) {
temp = f();
pz = &temp;
}
pz->g();
}
printf("%s: endn", __func__);
}
Conditional Logic Outside the Loop:
int main(int argc, char ** argv) {
(void)argc, (void)argv;
printf("%s: beginn", __func__);
{
const auto & z = f();
z.g();
}
{
const auto & z = s;
z.g();
}
printf("%s: endn", __func__);
}
1