Re: static class member variables

From: Maxim Yegorushkin (e-maxim_at_yandex.ru)
Date: 11/18/04


Date: 17 Nov 2004 19:09:35 -0500

On 17 Nov 2004 06:12:08 -0500, Eric <shoongi@yahoo.com> wrote:

> I have a static class member variable as follows:
>
> struct A
> {
> static void Set (int i) { v = i; }
> static int& Get () { return v; }
> static int v;
> };
>
> int A::v; // define A::v in the cpp file
> A::v will have external linkage and there will only be one instance of
> this variable in the executable:
>
> However, let's say I don't want to define the variable in the cpp file
> (eg. it's a template class and I don't want users to have to define the
> variable).

You can use a trick to place the static in *.h without getting multiple
simbol definitions linker error - place that static in a template base
class as follows:

    template<int dummy> struct statics { static int v; };
    template<int dummy> int statics<dummy>::v;

    struct A : private statics<1234>
    {
        // Get/Set are the same as before
    };

> Is there anything wrong with defining it in a static member function
> which returns a reference to the variable? Will there also always only
> be one copy of the local static variable? Any other unforseen problems?
> Thanks in
> advance for any comments.
>
> struct A
> {
> static void Set (int i) { v() = i; }
> static int& Get () { return v(); }
> static int& v()
> {
> static v;
> return v;
> }
> };

Probably, you forgot static keyword here. The code as it is written now
returns a dangling reference to the already evaporated local variable. You
can fix it as:

       static int& Get () { static int v; return v; }

-- 
Maxim Yegorushkin
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]


Relevant Pages


Loading