AI Features

Discussion: All Good Things Must Come to an End

Execute the code to understand the output and gain insights into constructors with local state variables.

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 Going Global puzzles, we learned about the lifetime and initialization differences between a global variable and a local variable:

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 ...