Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are local static objects created?

Tags:

c++

Chapter 6.1.1 of the book C++ Primer says the following:

Each local static object is initialized before the first time execution passes through the object’s definition. Local statics are not destroyed when a function ends; they are destroyed when the program terminates.

To check this, I ran the following code:

#include <iostream>

using std::clog;
using std::endl;

struct Bar {
    Bar() {
        clog << "constructing Num object" << endl;
    }

    int i = 0,
        j = 0;

    ~Bar() {
        clog << "destructing Num object" << endl;
    }
};

void foo() {
    clog << "foo() started" << endl;
    static Bar b;
    return;
}

int main() {
    if (true) {
        clog << "if-statement started" << endl;
        foo();
    }

    clog << "if-statement exited" << endl;

    return 0;
}

At this point in the book I haven't covered structs and classes yet, but it is my understanding that the function Bar() logs a message to the standard output when it gets created, and that b gets default initialized. If that is the case, then why does the output show that the object is constructed / initialized when control reaches static Bar b;, and not before it reaches this statement?

Output:

if-statement started
foo() started
constructing Num object
if-statement exited
destructing Num object
like image 653
L.S. Roth Avatar asked Jan 30 '26 08:01

L.S. Roth


1 Answers

When are local static objects created?

As your book says: "before the first time execution passes through the object’s definition".

More precisely, the standard's wording is:

Dynamic initialization of a block-scope variable with static storage duration or thread storage duration is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization.

I think you're getting too hung up on the word "before". 🙂

like image 186
Asteroids With Wings Avatar answered Jan 31 '26 22:01

Asteroids With Wings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!