1

I'm wondering what memory space was used when I declared a variable and initialize a value outside of a function or method, for example,

// CBar.h>
class CBar
{
public:
   CBar();
   ~CBar();
};

// CBar.cpp
std::string const NAME = "mr.foo";

CBar::CBar()
{
   std::cout << NAME << std::endl;
}

CBar::~CBar()
{
}

The NAME variable I declared outside of the methods. Is there any problem declaring and initializing this NAME variable? And everytime I create CBar instance the NAME variable still there?

Thanks.

domlao
  • 15,663
  • 34
  • 95
  • 134

2 Answers2

4

In your code, NAME is a static variable (like a global variable within the file CBar.cpp). It is instantiated once at the very beginning of your program and lives (the memory stays allocated) throughout the program.

The value/memory will always be accessible (from within CBar.cpp) no matter how many times you instantiate or delete CBar objects because the variable is independent of the CBar class.

More technically, the memory for the static exists in an initialized data segment. See this answer for a good explanation of memory regions: Global memory management in C++ in stack or heap?

Community
  • 1
  • 1
Turix
  • 4,470
  • 2
  • 19
  • 27
  • There is no such thing as "static linkage". (Static variables are not linkable.) – Dwayne Towell Oct 27 '13 at 03:27
  • @DwayneTowell: The point is correct, but the explanation is not. A name has "linkage" in C++ when it might denote the same entity declared in another scope. So while there is no "static linkage", there is "internal linkage", when an entity can be referred to from other scopes in the same translation unit using that name. A name with no linkage at all means the entity cannot be referred to by names from any other scopes, including scopes within the same translation unit. See C++11 3.5.2 for more. – Crowman Oct 27 '13 at 04:32
2

The NAME variable is global. It exists from before main() until after it returns. It could be linked to from another module if the following declaration were included in the other source file.

extern std::string const NAME;

If you do not want this to be allowed, you should declare it as shown below.

static std::string const NAME;

Now it only "pollutes" the identifier name space in CBar.cpp. If you want to avoid that, you need to make it a private/protected member variable of CBar.

Dwayne Towell
  • 8,154
  • 4
  • 36
  • 49
  • It actually gets internal linkage by default, since it's declared `const`. You'd have to explicitly add the `extern` to give it external linkage. – Crowman Oct 27 '13 at 04:27