static initialization misunderstanding

B

Brice Gagnage

Hello,

I have a header containing static const variables declared at file
scope. This header is protected against multiple inclusion
(#ifndef/#define). These variables are of a class type (CComBSTR, for
those who know COM/ATL programming):

static const CComBSTR var( L"var" );

From what I understood about static initialization, the compiler is
supposed to allocate memory for each static variable declared like that,
which will be shared at file scope. This means, if I'm right, that the
ctor of CComBSTR will be called one time for each variable.

The problem is that when I put a breakpoint on this declaration, the
ctor of this var is called more than one time. Where am I mistaking ?

Thanks in advance,
 
I

Ian Collins

Brice said:
Hello,

I have a header containing static const variables declared at file
scope. This header is protected against multiple inclusion
(#ifndef/#define). These variables are of a class type (CComBSTR, for
those who know COM/ATL programming):

static const CComBSTR var( L"var" );

From what I understood about static initialization, the compiler is
supposed to allocate memory for each static variable declared like that,
which will be shared at file scope. This means, if I'm right, that the
ctor of CComBSTR will be called one time for each variable.

The problem is that when I put a breakpoint on this declaration, the
ctor of this var is called more than one time. Where am I mistaking ?

By using "static". Each compilation unit will have its own copy of var.
 
B

Brice Gagnage

Le 10-07-2009 said:
By using "static". Each compilation unit will have its own copy of var.

Not using static doesn't change anything, the debugger goes through the
ctor many times.
 
B

Bart van Ingen Schenau

Not using static doesn't change anything, the debugger goes through the
ctor many times.

That is because in C++, namespace-scope objects that are declared
'const' are implicitly static.


Bart v Ingen Schenau
 
B

Brice Gagnage

Le 10-07-2009 said:
That is because in C++, namespace-scope objects that are declared
'const' are implicitly static.

Right, so is there a way of declaring a var shared among many .cpp, but
allocated only one time ?
 
B

Brice Gagnage

Le 10-07-2009 said:
That is because in C++, namespace-scope objects that are declared
'const' are implicitly static.

Ok I found a way to do what I was looking for:

globals.h: extern const CComBSTR var;
globals.cpp: const CComBSTR var( L"var" );

other.cpp: #include globals.h

var is correctly initialized after that :)

Thanks all,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
DewittMill
Top