Search⌘ K
AI Features

Discussion: All Good Things Must Come to an End

Explore the lifetime and initialization behaviors of global, local, and local static variables in C++. Understand dynamic initialization, object destruction order, and best practices for managing global variables to avoid common pitfalls.

Run the code

Now, it’s time to execute the code and observe the output.

C++ 17
#include <iostream>
#include <string>
struct Connection
{
Connection(const std::string &name) : name_(name)
{
std::cout << "Created " << name_ << "\n";
}
~Connection()
{
std::cout << "Destroyed " << name_ << "\n";
}
std::string name_;
};
Connection global{"global"};
Connection &get()
{
static Connection localStatic{"local static"};
return localStatic;
}
int main()
{
Connection local{"local"};
Connection &tmp1 = get();
Connection &tmp2 = get();
}

A quick recap

In the Hack the Planet! and ...

C++ 17
int id; // global variable, one instance throughout the whole program
void f()
{
int id = 2; // local variable, created anew each time `f` is called
}

In ...