473,769 Members | 7,388 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
16 2985
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; }

};


I strongly disagree. I am not sure, but it seems to me, that you've got
ODR violation here. The exact meaning of 'return v' is different in every
TU because of the fact that an unnamed namespace does have a name, though
hidden and distinct for every TU.

Aside from (possible) ODR violation, there are other problems. This places
a distinct instance of an object from the unnamed namespace in every TU
that includes the header with the unnamed namespace, what results in quite
different semantics because now every TU operates on an own instance of 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 #11

"Maxim Yegorushkin" <e-*****@yandex.ru > schrieb im Newsbeitrag
news:opshq9w3y9 ti5cme@wkcg6rir wp...
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; }

};
I strongly disagree. I am not sure, but it seems to me, that you've got
ODR violation here.

Don't think so. Since v has internal linkage....


Aside from (possible) ODR violation, there are other problems. This places
a distinct instance of an object from the unnamed namespace in every TU
that includes the header with the unnamed namespace, what results in quite
different semantics because now every TU operates on an own instance of v.


That IS a problem.
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 #12
"Thomas Mang" <no****@nospam. invalid> wrote...
"Maxim Yegorushkin" <e-*****@yandex.ru > schrieb im Newsbeitrag
news:opshq9w3y9 ti5cme@wkcg6rir wp...
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; }
>
> };
I strongly disagree. I am not sure, but it seems to me, that you've got
ODR violation here.

Don't think so. Since v has internal linkage....


A big misconception. 'v' has _external_ linkage, but it doesn't matter.
Every file that includes that header has its own 'v', since its name has
the name of the anonymous namespace added to it.
[..the other problem is correctly identified..]


V
Jul 22 '05 #13
In article <41************ ***********@use net.univie.ac.a t>, Thomas Mang
<no****@nospam. invalid> writes
"Maxim Yegorushkin" <e-*****@yandex.ru > schrieb im Newsbeitrag
news:opshq9w3y 9ti5cme@wkcg6ri rwp...
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; }
>
> };


I strongly disagree. I am not sure, but it seems to me, that you've got
ODR violation here.

Don't think so. Since v has internal linkage....


It doesn't, it has external linkage but with an unutterable name.
However that is not really relevant because there is a potential ODR
violation which ever way you take it. If the above header file is
included in more than one TU the definition of struct A will be an ODR
issue.
--
Francis Glassborow ACCU
Author of 'You Can Do It!' see http://www.spellen.org/youcandoit
For project ideas and contributions: http://www.spellen.org/youcandoit/projects
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #14
"Maxim Yegorushkin" <e-*****@yandex.ru > wrote in message
news:<opshq9w3y 9ti5cme@wkcg6ri rwp>...
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; }

};


I strongly disagree. I am not sure, but it seems to me, that you've got
ODR violation here. The exact meaning of 'return v' is different in every
TU because of the fact that an unnamed namespace does have a name, though
hidden and distinct for every TU.

Aside from (possible) ODR violation, there are other problems. This places
a distinct instance of an object from the unnamed namespace in every TU
that includes the header with the unnamed namespace, what results in quite
different semantics because now every TU operates on an own instance of v.

I understand my misconception. Thanks for pointing this out. I seem to
have been over enthusiastic about the clause 7.3.1.1 - Unnamed
namespaces para 2 which says something like this
"The use of the static keyword is deprecated when declaring objects in
a namespace scope (see annex depr); the unnamed-namespace provides a
superior alternative."

As has been pointed out this applies to "namespace scope" members only
and even with such variables this must be used with caution as the
generated namespace name(for the unnamed namespace) in each TU is
implementation dependent which may create binary differences of the
executable which is beyond programmers control.

But a doubt remains; since the standard does recommend it for
"namespace scope" variables, does it violate ODR for such variables?.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #15
Thomas Mang wrote:
"Maxim Yegorushkin" <e-*****@yandex.ru > schrieb im Newsbeitrag news:opshq9w3y9 ti5cme@wkcg6rir wp...
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; }
};


I strongly disagree. I am not sure, but it seems to me, that you've got
ODR violation here.


Don't think so. Since v has internal linkage....


No, v does not have internal linkage. Things inside the unnamed
namespace have external linkage. They just have a name that is known
only to the current translation unit, making them inaccessible from
other translation units. The ultimate effect is very similar to making
v static, but there are some subtle differences that must be understood.

The one-definition rule (ODR) violation is not with v, it is with A::Set
and A::Get. Within each translation unit, A::Set and A::Get refer to
the v that is unique to that translation unit. Therefore, A::Set and
A::Get are not the same in all translation units, which is not allowed.

--
David Olsen
qg********@yaho o.com

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 22 '05 #16
re**********@ho tmail.com (Renjith Mohan) wrote in message
news:<cd******* *************** ****@posting.go ogle.com>...

But a doubt remains; since the standard does recommend it for
"namespace scope" variables, does it violate ODR for such variables?.


In this context, you get ODR violations using either (deprecated)
namespace scope statics or a nameless namespace. Using a nameless
namespace doesn't make it any more wrong :-)

Point of interest: boost::bind uses a nameless namespace in a header
to define _1, _2 etc. (the parameter placeholders). I've yet to get a
grip on the pros and cons of this - not that it's something you have
to understand to use bind itself.
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 #17

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

Similar topics

29
4409
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
4616
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
5180
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
6247
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
8895
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
8383
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
5824
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
9423
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
10216
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
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
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
5310
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...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3965
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2815
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.