Why is a global object destructor called twice after initializing a reference to it?

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:

  1. A simple reference to the global s.
  2. 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 treats z itself as a local reference and calls the destructor of the object it refers to when z 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Why is a global object destructor called twice after initializing a reference to it?

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:

  1. A simple reference to the global s.
  2. 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 treats z itself as a local reference and calls the destructor of the object it refers to when z 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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật