473,794 Members | 2,748 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Static member use before its initialization

Class Bar in a program below contains two static members: v1 and v2 of
class Foo.
v1 is initialized before creating an instance of Bar, v2 v1 is
initialized after that instance.
No Foo-constuctor for v2 was called before line
"Bar b".
However, (temporary ?) instance for v2 was created in Bar::Bar(). How
was it created: without calling constructor?
------- foo.cpp -------
#include <iostream>
#include <vector>
using namespace std;

struct Foo : public vector<int>
{
Foo() { cout << "Foo::Ctor-0" << endl;}
Foo(size_t n) : vector<int> (n) { cout << "Foo::Ctor-1: n = " << n <<
endl;;}
};

struct Bar
{
static Foo v1;
static Foo v2;
static void Show(const char* const msg);
Bar();
};

Bar::Bar()
{
Show ("[Bar()-A]");

v1.push_back(0) ;
v2.push_back(0) ;

Show ("[Bar()-B]");
}

void Bar::Show(const char* const msg)
{
cout << msg << ": v1.size()" << v1.size() << ", v2.size() = " <<
v2.size() << endl;
}

Foo Bar::v1(100);
Bar b;
Foo Bar::v2(200);

int main()
{
Bar::Show ("[main] ");
return 0;
}
-----------------------

------- Run -------
Foo::Ctor-1: n = 100
[Bar()-A]: v1.size()100, v2.size() = 0
[Bar()-B]: v1.size()101, v2.size() = 1
Foo::Ctor-1: n = 200
[main] : v1.size()101, v2.size() = 200
-------------------


Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn

May 15 '06 #1
1 1373
Alex Vinokur wrote:
Class Bar in a program below contains two static members: v1 and v2 of
class Foo.
v1 is initialized before creating an instance of Bar, v2 v1 is
initialized after that instance.
No Foo-constuctor for v2 was called before line
"Bar b".
However, (temporary ?) instance for v2 was created in Bar::Bar().
No, you just accessed the uninitialized storage for v2.

How was it created: without calling constructor?


Your program has undefined behaviour since you use v2 before it has been
initialized. As for an explanation of the exact undefined behaviour you
are seeing, global objects have their memory zeroed before any other
initialization occurs. It just so happens that all-zeroed was valid for
your Foo object v2, so when v2.push_back(0) is called, it thinks it is
being called on an empty vector and the code operates accordingly.
However, your v2 constructor then runs so you end up leaking the memory
you just allocated.

Tom
May 15 '06 #2

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

Similar topics

15
2889
by: cppaddict | last post by:
I have class with two static member objects, one of type int and one of type vector<int>. static int myStaticMemberInt static vector<int> myStaticMemberVector; I know how to initialize the int member: MyClass::myStaticMemberInt = 99;
3
3614
by: DanielBradley | last post by:
Hello all, I have recently been porting code from Linux to cygwin and came across a problem with static const class members (discussed below). I am seeking to determine whether I am programming non-standard C++ or if the problem lies elsewhere. To summarize static const class members are not being accessed properly when accessed from a DLL by another external object file (not within the DLL). It only occurs when the static const...
3
1711
by: Tran Tuan Anh | last post by:
Dear all, I am new with C++ and very confused with some features. Really appreciate if you can explain to me some of stuffs below. I define a class: class A { static A* instance = 0; };
3
6388
by: Mike - EMAIL IGNORED | last post by:
MyClass { //I have a static member method: void static myMethod(); //and a static data member: static MyType myData; }; //In the .cpp file: void MyClass::myMethod()
8
8932
by: Per Bull Holmen | last post by:
Hey Im new to c++, so bear with me. I'm used to other OO languages, where it is possible to have class-level initialization functions, that initialize the CLASS rather than an instance of it. Like, for instance the Objective-C method: +(void)initialize Which has the following characteristics: It is guaranteed to be run
7
4033
by: Spoon | last post by:
Hello everyone, I have a Packet class I use to send packets over the Internet. All the packets sent in a session are supposed to share a common random ID. I figured I'd use a static const member inside my class. class Packet { static const int session_id;
9
8896
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
5
5622
by: desktop | last post by:
Why is this struct illegal: #include<iostream> struct debug { std::string d1 = "bob\n"; }; I get this error:
15
7873
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
2
2486
by: Ranganath | last post by:
Hi, Why is there a restriction that only integral types can be made static constant members of a class? For e.g., class B { private: static const double K = 10; };
0
9671
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
9518
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
10212
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...
0
9035
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...
1
7538
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
6777
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
5436
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...
1
4112
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
2919
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.