473,729 Members | 2,345 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

initializing static class variables

Hello,

When an "std::map<i nt, int> foobar;" statement appears in a C++ program
followed by a statement of the form "foobar[123];" where nothing has ever
been inserted at position 123 into map foobar, the C++ standard states
that a new element is created at position 123 and is initialized to
zero. That is, in this case, the pair (123, 0) is inserted into the
map.

I am interested in knowing what the standard says should happen in the
following case. Does the standard mandate that struct Foo's pointers be
initialized to zero as well, upon reference to hello[110], or does this
program lead to undefined behavior.

Thank you for your feedback and explanations,

Neil

#include <iostream>
#include <map>

struct Foo {
int *x;
int *y;
};

typedef std::map<int, Foo> Hello;

int main() {
Hello hello;
//initialize entiry structure, hence also its pointers, to zero
//(I believe this is according to the ANSI/ISO C++ standard too)
std::cout << hello[110].x << std::endl;
//hence dereferencing zero memory address causes segfault
//std::cout << *hello[110].x << std::endl;
//hence same goes for assigning
*hello[110].x = 112;
}
Jul 22 '05 #1
11 2552

I believe the STL standard says an object will be constructed
with the default constructor in this situation. Since you don't have
one, the values of x and y will be undefined (garbage) when you
insert a new key

dave

"Neil Zanella" <nz******@cs.mu n.ca> wrote in message
news:b6******** *************** ***@posting.goo gle.com...
Hello,

When an "std::map<i nt, int> foobar;" statement appears in a C++ program
followed by a statement of the form "foobar[123];" where nothing has ever
been inserted at position 123 into map foobar, the C++ standard states
that a new element is created at position 123 and is initialized to
zero. That is, in this case, the pair (123, 0) is inserted into the
map.

I am interested in knowing what the standard says should happen in the
following case. Does the standard mandate that struct Foo's pointers be
initialized to zero as well, upon reference to hello[110], or does this
program lead to undefined behavior.

Thank you for your feedback and explanations,

Neil

#include <iostream>
#include <map>

struct Foo {
int *x;
int *y;
};

typedef std::map<int, Foo> Hello;

int main() {
Hello hello;
//initialize entiry structure, hence also its pointers, to zero
//(I believe this is according to the ANSI/ISO C++ standard too)
std::cout << hello[110].x << std::endl;
//hence dereferencing zero memory address causes segfault
//std::cout << *hello[110].x << std::endl;
//hence same goes for assigning
*hello[110].x = 112;
}

Jul 22 '05 #2
On Thu, 29 Jul 2004 18:07:27 -0700, Dave Townsend <da********@com cast.net>
wrote:

I believe the STL standard says an object will be constructed
with the default constructor in this situation. Since you don't have
one, the values of x and y will be undefined (garbage) when you
insert a new key

dave

I don't believe that is correct, the standard says that hello[110] is
equivalvent to

(*((insert(make _pair(100,Foo() ))).first)).sec ond;

he crucial bit is Foo() which is value initialisation not default
initialisation. For value initialisation of Foo, x and y will be zero
initialised.

However I think value iniitalisation is a fairly new concept in the
C++ standard and I wouldn't be surprised if a compiler got this wrong.

Also I'm not completely certain of this, and I'm really just posting to
put the alternative view. The releveant sections of the standard are 8.5,
23.3.1.2, 5.2.3 for anyone who want's to check this out. Maybe one of the
gurus could clear this up.

Either way the safe thing to do is to add a default constructor to Foo.

john
"Neil Zanella" <nz******@cs.mu n.ca> wrote in message
news:b6******** *************** ***@posting.goo gle.com...
Hello,

When an "std::map<i nt, int> foobar;" statement appears in a C++ program
followed by a statement of the form "foobar[123];" where nothing has
ever
been inserted at position 123 into map foobar, the C++ standard states
that a new element is created at position 123 and is initialized to
zero. That is, in this case, the pair (123, 0) is inserted into the
map.

I am interested in knowing what the standard says should happen in the
following case. Does the standard mandate that struct Foo's pointers be
initialized to zero as well, upon reference to hello[110], or does this
program lead to undefined behavior.

Thank you for your feedback and explanations,

Neil

#include <iostream>
#include <map>

struct Foo {
int *x;
int *y;
};

typedef std::map<int, Foo> Hello;

int main() {
Hello hello;
//initialize entiry structure, hence also its pointers, to zero
//(I believe this is according to the ANSI/ISO C++ standard too)
std::cout << hello[110].x << std::endl;
//hence dereferencing zero memory address causes segfault
//std::cout << *hello[110].x << std::endl;
//hence same goes for assigning
*hello[110].x = 112;
}



Jul 22 '05 #3
John,

thanks for point out this subtlety. Can you post an example which
demonstrates the difference, I've heard mention of these two types
of initialization but never got on to what the difference was.

thanks, dave

"John Harrison" <jo************ *@hotmail.com> wrote in message
news:opsbxp9wq7 212331@andronic us...
On Thu, 29 Jul 2004 18:07:27 -0700, Dave Townsend <da********@com cast.net>
wrote:

I believe the STL standard says an object will be constructed
with the default constructor in this situation. Since you don't have
one, the values of x and y will be undefined (garbage) when you
insert a new key

dave


I don't believe that is correct, the standard says that hello[110] is
equivalvent to

(*((insert(make _pair(100,Foo() ))).first)).sec ond;

he crucial bit is Foo() which is value initialisation not default
initialisation. For value initialisation of Foo, x and y will be zero
initialised.

However I think value iniitalisation is a fairly new concept in the
C++ standard and I wouldn't be surprised if a compiler got this wrong.

Also I'm not completely certain of this, and I'm really just posting to
put the alternative view. The releveant sections of the standard are 8.5,
23.3.1.2, 5.2.3 for anyone who want's to check this out. Maybe one of the
gurus could clear this up.

Either way the safe thing to do is to add a default constructor to Foo.

john
"Neil Zanella" <nz******@cs.mu n.ca> wrote in message
news:b6******** *************** ***@posting.goo gle.com...
Hello,

When an "std::map<i nt, int> foobar;" statement appears in a C++ program
followed by a statement of the form "foobar[123];" where nothing has
ever
been inserted at position 123 into map foobar, the C++ standard states
that a new element is created at position 123 and is initialized to
zero. That is, in this case, the pair (123, 0) is inserted into the
map.

I am interested in knowing what the standard says should happen in the
following case. Does the standard mandate that struct Foo's pointers be
initialized to zero as well, upon reference to hello[110], or does this
program lead to undefined behavior.

Thank you for your feedback and explanations,

Neil

#include <iostream>
#include <map>

struct Foo {
int *x;
int *y;
};

typedef std::map<int, Foo> Hello;

int main() {
Hello hello;
//initialize entiry structure, hence also its pointers, to zero
//(I believe this is according to the ANSI/ISO C++ standard too)
std::cout << hello[110].x << std::endl;
//hence dereferencing zero memory address causes segfault
//std::cout << *hello[110].x << std::endl;
//hence same goes for assigning
*hello[110].x = 112;
}


Jul 22 '05 #4
On Thu, 29 Jul 2004 22:26:07 -0700, Dave Townsend <da********@com cast.net>
wrote:
John,

thanks for point out this subtlety. Can you post an example which
demonstrates the difference, I've heard mention of these two types
of initialization but never got on to what the difference was.

thanks, dave


Well I don't want to sound more certain than I am, but here goes.

8.5 para 7 of the standard says

An object whose initialiser is an empty set of parentheses i.e., (), shall
be value-initialized.

So I reckon in this code

class Bar
{
Bar() : foo() {}
Bar(int) {}
private:
Foo foo;
};

the first constructor value initialises foo, and the second default
initialises it.

Ditto

Foo* foo = new Foo(); // value initialisation
Foo* foo2 = new Foo; // default initialisation

john
Jul 22 '05 #5
Interesting, you must all be referring to the new C++ standard
available
from ANSI (at USD 18.0 for the electronic version). It also seems like
the
older 1998 standard has been discontinued.

http://webstore.ansi.org/ansidocstor...C+14882%2D2003

So what is the difference between default initialization
and value initialization? Is this something introduced
in the 2003 standard?

Thanks,

Neil

class Foo {
public:
Foo() { }
};

class Bar {
public:
Bar(): foo() { }
Bar(int) { }
private:
Foo foo;
};

int main() {
Foo *foo = new Foo();
Foo *foo2 = new Foo;
Foo foo3;
Foo foo4();
}
Jul 22 '05 #6
On 31 Jul 2004 11:44:01 -0700, Neil Zanella <nz******@cs.mu n.ca> wrote:
Interesting, you must all be referring to the new C++ standard
available
from ANSI (at USD 18.0 for the electronic version). It also seems like
the
older 1998 standard has been discontinued.

http://webstore.ansi.org/ansidocstor...C+14882%2D2003

So what is the difference between default initialization
and value initialization? Is this something introduced
in the 2003 standard?

Thanks,

Neil


I believe it was introduced in 2003 standard but I can't be sure since I
don't have the 1998 standard available.

I guess the difference is best illustrated with an example

struct Foo
{
int x;
};

The standard says (8.5 para 5) that if Foo is default initialised then its
default constructor is called. This is obviously an implicit default
constructor and 12.1 para 7 and 12.6.2 para 4 together say that x is not
initialised in this case (i.e. it has an undefined value).

Hoever 8.5 para 5 says that if Foo is value initialised then because Foo
does not have a user-declared constructor each of its members is value
initialised. And when a scalar type is value initalsed it is in fact zero
initialised.

So

#include <iostream>
using namespace std;

struct Foo
{
int x;
};

int main()
{
int* a = new int;
cout << *a << '\n';
int* b = new int();
cout << *b << '\n';
Foo* c = new Foo;
cout << c->x << '\n';
Foo* d = new Foo();
cout << d->x << '\n';
}

Output with MSVC++ 7.1

-842150451
0
-842150451
0

But I'm still learning this stuff myself, so watch out I could easily be
wrong.

john
Jul 22 '05 #7
On Sat, 31 Jul 2004 20:12:43 +0100, "John Harrison"
<jo************ *@hotmail.com> wrote:

I believe it was introduced in 2003 standard but I can't be sure since I
don't have the 1998 standard available.

I guess the difference is best illustrated with an example

struct Foo
{
int x;
};

The standard says (8.5 para 5) that if Foo is default initialised then its
default constructor is called. This is obviously an implicit default
constructor and 12.1 para 7 and 12.6.2 para 4 together say that x is not
initialised in this case (i.e. it has an undefined value).

Hoever 8.5 para 5 says that if Foo is value initialised then because Foo
does not have a user-declared constructor each of its members is value
initialised. And when a scalar type is value initalsed it is in fact zero
initialised.
[....]
But I'm still learning this stuff myself, so watch out I could easily be
wrong.

john


Default initilization when viewed from the 1998 and 03 version of the
standard seem contradictory.

The 1998 standard for C++ (ISO/IEC 14882-1998) says:

"An object whose initializer is an empty set of parentheses, i.e., (),
shall be default-initialized."

A little before that, it says:

"To default-initialize an object of type T means:
** if T is a non-POD class type (clause 9), the default constructor
for T is called (and the initialization is ill-formed if T has no
accessible default constructor);
** if T is an array type, each element is default-initialized;
** otherwise, the storage for the object is zero-initialized."

(Section 8.5, Initializers)

So given

struct data_t
{
int Idx;
int Jdx;
int Kdx;
} data;

data_t type is a POD class type (plain old data), so with empty
parentheses, it should be zero-initialized.

data_t() is not exactly a constructor call. It denotes a temporary
object of type data_t, constructed with default initialization.

So data(data_t()) initializes the object named "data" with a
temporary, default-initialized object of its type, and for this type
default initialization is zero-initialization.

Note that some compilers may not do this right. In any event, it
seems to me the 03 version of the standard refers to this as value
initilization.

Mark
--
[ C++ FAQ: http://www.parashift.com/c++-faq-lite/ ]
Jul 22 '05 #8
On Sat, 31 Jul 2004 23:28:10 -0400, Mark <ma**********@h otmail.com> wrote:
On Sat, 31 Jul 2004 20:12:43 +0100, "John Harrison"
<jo************ *@hotmail.com> wrote:

I believe it was introduced in 2003 standard but I can't be sure since I
don't have the 1998 standard available.

I guess the difference is best illustrated with an example

struct Foo
{
int x;
};

The standard says (8.5 para 5) that if Foo is default initialised then
its
default constructor is called. This is obviously an implicit default
constructor and 12.1 para 7 and 12.6.2 para 4 together say that x is not
initialised in this case (i.e. it has an undefined value).

Hoever 8.5 para 5 says that if Foo is value initialised then because Foo
does not have a user-declared constructor each of its members is value
initialised. And when a scalar type is value initalsed it is in fact
zero
initialised.
[....]

But I'm still learning this stuff myself, so watch out I could easily be
wrong.

john


Default initilization when viewed from the 1998 and 03 version of the
standard seem contradictory.

The 1998 standard for C++ (ISO/IEC 14882-1998) says:

"An object whose initializer is an empty set of parentheses, i.e., (),
shall be default-initialized."


That's directly contradicted by the 2003 standard which says value
initialised.

A little before that, it says:

"To default-initialize an object of type T means:
** if T is a non-POD class type (clause 9), the default constructor
for T is called (and the initialization is ill-formed if T has no
accessible default constructor);
** if T is an array type, each element is default-initialized;
** otherwise, the storage for the object is zero-initialized."

(Section 8.5, Initializers)

So given

struct data_t
{
int Idx;
int Jdx;
int Kdx;
} data;

data_t type is a POD class type (plain old data), so with empty
parentheses, it should be zero-initialized.
Assuming you are talking about the 1998 standard I don't think so. Look up
the definition of compiler generated default constructor. I think you will
see that it says Idx, Jdx and Kdx remain uninitialised not zero
initialised.

data_t() is not exactly a constructor call. It denotes a temporary
object of type data_t, constructed with default initialization.

So data(data_t()) initializes the object named "data" with a
temporary, default-initialized object of its type, and for this type
default initialization is zero-initialization.

Note that some compilers may not do this right. In any event, it
seems to me the 03 version of the standard refers to this as value
initilization.


And that's the crucial difference, because value initialisation does not
use the compiler generated default constructor.

john
Jul 22 '05 #9
On Sun, 01 Aug 2004 07:36:46 +0100, "John Harrison"
<jo************ *@hotmail.com> wrote:

[...]
(Section 8.5, Initializers)

So given

struct data_t
{
int Idx;
int Jdx;
int Kdx;
} data;

data_t type is a POD class type (plain old data), so with empty
parentheses, it should be zero-initialized.


Assuming you are talking about the 1998 standard I don't think so. Look up
the definition of compiler generated default constructor. I think you will
see that it says Idx, Jdx and Kdx remain uninitialised not zero
initialised.

If I run test program below through Visual Studio 7.1. Then run said
program through Borland C++ Builder 4. The end result. Builder 4 did
zero initialize the struct while Visual Studio didn't.
# include<cstdio>

class test
{
private:
struct data_t
{
int mem1;
double mem2;
char mem3;
double mem4[50];
} data;
public:
test()
:data(data_t()) //zero initialises data
{
printf( "mem1 = %d\n", data.mem1 );
printf( "mem2 = %f\n", data.mem2 );
}
};

int main(int argc, char* argv[])
{
test mytest;
}

Mark
--
[ C++ FAQ: http://www.parashift.com/c++-faq-lite/ ]

Jul 22 '05 #10

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

Similar topics

14
10643
by: Avi Uziel | last post by:
Hi All, I'm writing a Windows DLL which contain some utility classes. One of my classes is Singleton, therefore contain some static members. I'm using VC6 and linking to the DLL statically. My question is where is the correct (and best way) to initialize theses variables? If I initialize them in the class CPP (in the DLL) then I get linkage error when I try to link my project with the LIB, and I don't want to make the user initialize...
2
3589
by: Drew McCormack | last post by:
I am getting an error in g++ 4.0.0 that I did not get in g++ 3.4. I have a header with the following const variables with namespace scope: namespace Periphery { extern const double ProtonMassInAtomicUnits = 1836.152755656068; } I try to use these in another header to initialize static const member
1
417
by: Andreas Boehm | last post by:
Hi *.*, does the standard meanwhile define something about initializing variables by the compiler? I think, it is a side-effect of the OS used, if undefined global (static) variables are initialized to zero. What does the standard define for this? thanx Andreas
0
1114
by: Adam Smith | last post by:
Are there any drawbacks to initializing static member variables for classes used in an asp.net application within application_start? My classes have arraylist like tables, which cache information so that I don't have to hit the database every call. I would like to initialize these tables through calling a static class function, Init(), in application start. Thanks.
3
5708
by: Diebels | last post by:
Hi, I have some problems using static variables which results in a core dump. I have attached code and coredump to the end of my message. I am trying to implement a kind of factory design. I have a base class with several sub classes. In runtime I want to create a instance of a sub class and assign it to a base class pointer. Nothing fancy about that. I also want to be able in runtime to decide witch type of sub class that is to be...
17
2616
by: Calle Pettersson | last post by:
Coming from writing mostly in Java, I have trouble understanding how to declare a member without initializing it, and do that later... In Java, I would write something like public static void main(String args) { MyType aMember; ... aMember = new MyType(...) ... } However, in C++ this does not seem to work. I declare in class (it's
10
7869
by: sunil | last post by:
Hello, I am new to c# . I have some basic programming doubts. Please help me in clarifying these doubts. I want to initialize a static and readonly field with a value returned by a static method. How ever, when I am debugging, that method is not being called. So I am not able to figure out, whether the field is getting initialized properly or not. Please explain this behavior Thanks in advance
1
9157
by: david.baird | last post by:
I have 3 classes, 1 which does not use templates, CGood, and 2 which do use templates, CBad, and COkay. I believe that all of them should work, but only CGood and COkay are working for me. CBad fails to compile. class CGood { public: typedef int arr_t; static const arr_t bar;
8
2770
by: John | last post by:
Hello, is there any compiler option for g++ for initializing static members of the class. Due to some unknown reason, static member in one of our c++ application is not getting initialized properly. Please help me on this. Thanks,
6
3243
by: Grey Alien | last post by:
class A { public: A(const B& ref); private: static B& b ; }; How may b be initialized ?
0
8761
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
9426
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
9281
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
9200
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
4525
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
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
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
2
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2163
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.