473,757 Members | 8,356 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

static class member variables

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).
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;
}
};

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #1
16 2983
Eric 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 could define the entire template in the header file.

template <typename X>
struct A
{
static void Set (int i) { v = i; }
static int& Get () { return v; }
static int v;
};

template <typename X>
int A::v; // define A::v in the header file

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;
}
};

In theory, this will work as well, however, some linkers will violate
the "only one copy" rule when you start using DLL's.

Having said that, this is the ONLY way to guarentee the order of
construction in case you're constructing many inter-related objects
before calling main(), so it is a recomended practice.

Jul 22 '05 #2
On 17 Nov 2004 06:12:08 -0500, Eric <sh*****@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++.m oderated. First time posters: Do this! ]
Jul 22 '05 #3
"Maxim Yegorushkin" <e-*****@yandex.ru > wrote in message news:<op******* *******@devlx00 7.ipcb.net>...

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
};


Just a slight tidy up:

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

struct A : private statics<>
{
// 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; <------------------ missing int
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; }

Look again. The only mistake is a missing int on the line I marked
(which of course will compile on older compilers, since the int was
implied in pre-standard C++). (Also, Get should probably return by
value, but that's a design point rather than an error.)
James

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #4
Hello Maxim Yegorushkin,

Maxim Yegorushkin schrieb:
On 17 Nov 2004 06:12:08 -0500, Eric <sh*****@yahoo. com> wrote:

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; }

Your description is somewhat misleading. I think the actual error, the
OP made was, that its declaration
of the local static in v misses a type. This looks like an MSVC
compiler: Its a real **shame** that even MSVC7.1
does allow implicit int declarations!! (In this case the compiler was
taking the right "guess", but what about
the next time??).

Furtheron it seems reasonable that the OP's Get function signature
should be changed to

struct A
{
...
static int Get () { return v(); }
...
};

because otherwise The Set function does not make very much sense...

Last but not least: Your proposal to use the template helper class is a very
cool idea, Maxim!

Greetings from Bremen,

Daniel


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

Jul 22 '05 #5
"Maxim Yegorushkin" <e-*****@yandex.ru > wrote in message news:<op******* *******@devlx00 7.ipcb.net>...
On 17 Nov 2004 06:12:08 -0500, Eric <sh*****@yahoo. com> wrote:
...
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.


Where?
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; }


static int& v () { static int v; return v; } // ?

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #6
"Maxim Yegorushkin" <e-*****@yandex.ru > wrote in message
news:<op******* *******@devlx00 7.ipcb.net>...
On 17 Nov 2004 06:12:08 -0500, Eric <sh*****@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).

Another solution is to use an unnamed namespace which is semantically
equivalent to internal linkage and is a mcuh more simple and elegant
solution.
Thus in a header file you can do this.
namespace
{
int v;
}
struct A
{
static void Set (int i) { v = i; }
static int& Get () { return v; }

};

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

Jul 22 '05 #7
On 19 Nov 2004 07:59:16 -0500, Daniel Krügler (ne Spangenberg)
<ds*@bdal.de> wrote:

[]
Your description is somewhat misleading.
I agree, that was not a well thought answer.
Last but not least: Your proposal to use the template helper class is a
very cool idea, Maxim!


I've stolen the idea from Dinkum STL implementation where it's used for
std::ios_base:: flags (in, out, ate, etc.).

--
Maxim Yegorushkin

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #8

"Renjith Mohan" <re**********@h otmail.com> schrieb im Newsbeitrag
news:cd******** *************** ***@posting.goo gle.com...
"Maxim Yegorushkin" <e-*****@yandex.ru > wrote in message
news:<op******* *******@devlx00 7.ipcb.net>...
On 17 Nov 2004 06:12:08 -0500, Eric <sh*****@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).

Another solution is to use an unnamed namespace which is semantically
equivalent to internal linkage and is a mcuh more simple and elegant
solution.
Thus in a header file you can do this.
namespace
{
int v;
}
struct A
{
static void Set (int i) { v = i; }
static int& Get () { return v; }

};


Not a clever solution.

v is not tied to class A by any means and can be accessed directly without
any A object / operator ::.
Also, try to use this with multiple translation units, each changing and
reading v (via the functions provided in A). Surprise, surprise (at least
when the semantic of the OP is intended).
Thomas

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #9
Renjith Mohan wrote:
Another solution is to use an unnamed namespace which is semantically
equivalent to internal linkage and is a mcuh more simple and elegant
solution.
Thus in a header file you can do this.
namespace
{
int v;
}
struct A
{
static void Set (int i) { v = i; }
static int& Get () { return v; }

};


An unnamed namespace in a header file? Each of the translation units
that includes it will have its own copy of v, then. :(

--
Seungbeom Kim

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

Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

29
4405
by: Alexander Mahr | last post by:
Dear Newsgroup, I'm somehow confused with the usage of the static keyword. I can see two function of the keyword static in conjunction with a data member of a class. 1. The data member reffers in all objects of this class to the same data Or in other word by using the static keyword all objects of one class can share data. (This is what I want)
11
4614
by: Roger Leigh | last post by:
The C++ book I have to hand (Liberty and Horvath, Teach yourself C++ for Linux in 21 Days--I know there are better) states that "static member functions cannot access any non-static member variables". However, this doesn't seem entirely correct. It also doesn't mention whether static member functions can access protected and private member data and methods (and I couldn't spot this in the FAQ). I have a class row<Row> which derives from...
25
5177
by: Sahil Malik [MVP] | last post by:
So here's a rather simple question. Say in an ASP.NET application, I wish to share common constants as static variables in global.asax (I know there's web.config bla bla .. but lets just say I wanna use global.asax) --- Would you declare your static var as --- public static int x ;
11
3843
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you experts. I would like to produce Javascript classes that can be "subclassed" with certain behaviors defined at subclass time. There are plenty of ways to do this through prototyping and other techniques, but these behaviors need to be static and...
1
3171
by: mangalalei | last post by:
A static data member can be of the same class type as that of which it is a member. A nonstatic data member is restricted to being declared as a pointer or a reference to an object of its class. And I haved used the sizeof operator to test a class which has a static data member, the class size is all the nonstatic data member except the static data member. In compiler's view, is the static data member constructed after the whole class...
5
3608
by: mast2as | last post by:
Hi guys Here's the class I try to compile (see below). By itself when I have a test.cc file for example that creates an object which is an instance of the class SpectralProfile, it compiles fine. 1 / Now If I move the getSpectrumAtDistance( const T &dist ) method definition in SpectralProfofile.cc let's say the compiler says core/profile.cc:199: error: `kNumBins' was not declared in this scope
55
6244
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
9
8894
by: Jess | last post by:
Hello, I was told that if I declare a static class constant like this: class A{ static const int x = 10; }; then the above statement is a declaration rather than a definition. As I've *defined* "x"'s value to be 10, isn't above statement a
17
8381
by: Juha Nieminen | last post by:
As we know, the keyword "inline" is a bit misleading because its meaning has changed in practice. In most modern compilers it has completely lost its meaning of "a hint for the compiler to inline the function if possible" (because if the compiler has the function definition available at an instantiation point, it will estimate whether to inline it or not, and do so if it estimates it would be beneficial, completely regardless of whether...
4
5823
by: aaragon | last post by:
Hi everyone, I have a linking error when using gcc4.2 and static member variables. The class template definition is something around the following: template<> class Element<L2_t: public Element_common<L2, Side<2,2 { public:
0
9489
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9298
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10072
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9906
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9885
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8737
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6562
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5172
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2698
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.