Re: const static initialization in Visual Studio
On Sep 20, 6:11 am, Barry <dhb2...@gmail.com> wrote:
Victor Bazarov wrote:
Barry wrote:
Victor Bazarov wrote:
t wrote:
Lippman's C++ Primer says that if you initialize a const static data
member in a class, you still need to define the member outside the
class but without an initializer.
I tried it using Visual C++ 2005 Express edition and get this error:
1>Account.obj : error LNK2005: "private: static int const
Account::period" (?period@Account@@0HB) already defined in Account
Main.obj
Is this one of those things that vary by compiler? Is what Lippman
said from Standard C++?
Yes. But it's only required for the variables that are used as
l-values (like when taking their address or binding a reference to
Are you sure? where in standard mention this.
Do you have a copy of the Standard? Then use it. If not, get one.
Well, I tried, but couldn't locate the content.
:-)
=A73.2, paragraphes 2 and 3. The 1998 version of the standard
says:
An expression is potentially evaluated unless either it is
the operand of the sizeof operator, or it is the operand of
the typeid operator and does not designate an lvalue of
polymorphic class types. An object [Account::period is an
object] or non-overloaded function is *used* if its name
appears in a potentially-evaluated expression. [Lot's of
other things are used whenever...]
Every program shall contain exactly one definition of every
non-inline function or object that is used in that program;
no diagnostic required.
There isn't even the exception that Victor mentionned; if you
*use* Account::period, you must define it in exactly one
translation unit. (The declaration in the class definition is
just that, a declaration. See =A73.1/2: "A declaration is a
definition unless [...], it declares a static data member in a
class declaration.)
The current draft is similar, but has added text in =A73.2 to the
effect that if the object qualifies for use in an integral
constant expression, and all of its uses involve an immediate
lvalue to rvalue conversion, then no definition is necessary.
(Basically, the exception to the rule that Victor mentionned.)
(And yes, it is sometimes difficult to find the correct location
in the standard.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34