Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static global std::unique_ptr disappears

Tags:

c++

static

I probably misunderstood how static objects work. Suppose following

common.hpp

struct common {};
static std::unique_ptr<common> global_ptr;

foo.cpp

#include "common.hpp"
void bar();
int main()
{
    global_ptr = std::make_unique<common>();
    bar();
}

bar.cpp

#include "common.hpp"
void bar()
{
    *global_ptr; // crashes, because global_ptr is empty
}

I am able to debug such situation, and &global_ptr is different in main() and bar(), why is that? global_ptr is definitely initialized in main(), I can use it without problem, but why global_ptr in bar() seems unitialized?

like image 812
Zereges Avatar asked Aug 01 '26 18:08

Zereges


2 Answers

static variable at global and namespace scope means internal linkage.

The name can be referred to from all scopes in the current translation unit.

It means global_ptr in different translation unit are different objects. The static variable is not visible outside of its own translation unit. There might be many objects with the name global_ptr, but only one per translation unit.

If you just want a global variable, you could declare it in common.hpp as:

extern std::unique_ptr<common> global_ptr;

and define it in the cpp file (might be common.cpp):

std::unique_ptr<common> global_ptr;
like image 81
songyuanyao Avatar answered Aug 04 '26 07:08

songyuanyao


Globals behave like your intended behavior without the static keyword. Static means that the global is actually local to the translation unit. Your confusion comes from the fact that static means different things in global scope and in function scope.

like image 39
Dani Avatar answered Aug 04 '26 06:08

Dani



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!