473,654 Members | 3,107 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using objects without ever creating an instance - recommendable?

Hi everyone!

I am debugging a big piece of code on the search for memory leaks,
using g++ under suse 9.3.
Since I'm trying to eliminate ALL memory leaks, I now stumbled upon a
class foo that is not ever instantiated (thus no constructor or
destructor ever called), but instead, all of its member variables are
defined as static in the according .cpp file, and it's methods are
invoked by calling foo::bar(...) to invoke method "bar(...)".

foo.h:
----------------
class foo {
public:
foo() {};
~foo() {};
static void bar (const char *);

private:
static char * myString;
static int myInt;
}

foo.cpp:
-----------------
/* definition of static members */
char *foo::myString;
int foo::myInt;

void foo::bar (const char *someString) {
myString = (char *) someString;
myInt = 1;
}
------------------

main.cpp:
------------
#include "foo.h"

int main() {
foo::bar ("Hello World!");
}
--------------
>From my understanding of C, the line
myString = (char *) someString;
stores a copy of the pointer to the parameter given to foo::bar in
myString, which can cause undefined behaviour, because the parameter
string is a (const char *) and loses validity after the function exits.

Question no. 1: Is that correct?
Question no. 2: Is the usage of classes without an instance excusable
under ANY circumstances? I totally disapprove of this style, but maybe
it's just my lack of understanding of how objects work?

What I see is that there is no defined point to free the memory pointed
to
by any member variables of class foo - the job normally done by a
destructor.

Question no. 3:
If - in order to solve this - I create an instance myFoo of class foo,
and remove the
declarations of static member variables in the foo.cpp, can I be sure
that
I will get an error at compile time, if I forget to change any access
to the
variables from foo::myString to myFoo->myString?
That last question seems obvious to answer, but I want a 2nd opinion :)

Regards,

Lars Uffmann

Aug 1 '06 #1
3 1836
la**********@rw th-aachen.de wrote:
I am debugging a big piece of code on the search for memory leaks,
using g++ under suse 9.3.
Since I'm trying to eliminate ALL memory leaks, I now stumbled upon a
class foo that is not ever instantiated (thus no constructor or
destructor ever called), but instead, all of its member variables are
defined as static in the according .cpp file, and it's methods are
invoked by calling foo::bar(...) to invoke method "bar(...)".

foo.h:
----------------
class foo {
public:
foo() {};
~foo() {};
static void bar (const char *);

private:
static char * myString;
Do the contents of this "string" ever change? No, I don't mean the
value of the pointer, I mean, do you ever change individual chars in
this "string"? If not, it should be declared a pointer to const char:

static char const* myString;
static int myInt;
}

foo.cpp:
-----------------
/* definition of static members */
char *foo::myString;
And here too

char const* foo::myString;
int foo::myInt;

void foo::bar (const char *someString) {
myString = (char *) someString;
If 'myString' is a pointer to const char, there will be no need to
cast anything.
myInt = 1;
}
------------------

main.cpp:
------------
#include "foo.h"

int main() {
foo::bar ("Hello World!");
}
--------------
>From my understanding of C, the line
myString = (char *) someString;
stores a copy of the pointer to the parameter
No. It "stores a copy of the pointer". Not "to the parameter".
given to foo::bar in
myString, which can cause undefined behaviour, because the parameter
string is a (const char *) and loses validity after the function
exits.
No, it does not. The value does not lose validity.
Question no. 1: Is that correct?
No.
Question no. 2: Is the usage of classes without an instance excusable
under ANY circumstances?
Sure.
I totally disapprove of this style, but maybe
it's just my lack of understanding of how objects work?
Static data members are singletons. If the program design calls for
a singleton, use it.
What I see is that there is no defined point to free the memory
pointed to
by any member variables of class foo - the job normally done by a
destructor.
There is no need - objects with static duration are created at the start
of the program and disposed of at the end of the program. If the type
of a static object has a constructor, it will be called, same for the
destructor. In your example, the static objects are of the built-in
types, no constructor or destructor exists.
Question no. 3:
If - in order to solve this - I create an instance myFoo of class foo,
and remove the
declarations of static member variables in the foo.cpp, can I be sure
that
I will get an error at compile time, if I forget to change any access
to the
variables from foo::myString to myFoo->myString?
WHY? What for? Does the program work? If it ain't broke, don't fix it.
That last question seems obvious to answer, but I want a 2nd opinion
:)
Happy to provide one.

BTW, what book on C++ are you currently reading?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 1 '06 #2
Victor Bazarov schrieb:
la**********@rw th-aachen.de wrote:
private:
static char * myString;
Do the contents of this "string" ever change? No, I don't mean the
value of the pointer, I mean, do you ever change individual chars in
this "string"? If not, it should be declared a pointer to const char:
Don't change, but it's pretty irrelevant because I was simplifying for
the example. The real code here uses lots of pointers to changing data
as member variables of class "foo".
From my understanding of C, the line
myString = (char *) someString;
stores a copy of the pointer to the parameter
No. It "stores a copy of the pointer". Not "to the parameter".
Still unclear. Given someString points to memory address X, then
after the assignment of myString, myString also points to memory
address X, right? That's what I meant.

myString, which can cause undefined behaviour, because the parameter
string is a (const char *) and loses validity after the function
exits.
No, it does not. The value does not lose validity.
Oh okay - I didn't know that. So if you store a pointer to a
const char passed to a function, the memory reserved for the
string during the function call stays untouched?
Question no. 2: Is the usage of classes without an instance excusable
under ANY circumstances?
Sure.
Mkay...
Static data members are singletons. If the program design calls for
a singleton, use it.
Thanks for the keyword...
http://en.wikipedia.org/wiki/Singleton_pattern
cleared up a few of my questions about how it is designed in this code
here. According to wiki, the constructor should be made either private
or protected, is NO constructor achieving the same effect? This class
has none.
For debugging purposes, I made it a normal class now and am using only
1 instance of it.
There is no need - objects with static duration are created at the start
of the program and disposed of at the end of the program. If the type
of a static object has a constructor, it will be called, same for the
destructor. In your example, the static objects are of the built-in
types, no constructor or destructor exists.
Hmm... so that means when the program exits - using exit (0); -
mtrace would NOT detect a memory leak unless there is some bug in the
code?

WHY? What for? Does the program work? If it ain't broke, don't fix it.
Nope - program has some huge memory leaks - over 200 megabytes of log
file from mtrace(). I am trying to fix them one by one, so I'm changing
everything that mtrace identifies as memory leak when I do a chain of
return; - at any point in the program to exit to the main routine and
then exit the
application.

The memory leaks make the code behave unpredictable and the behaviour
changes even on introduction of cerr-statements.
BTW, what book on C++ are you currently reading?
None, I just used the "foo" term because I saw it in lots of examples
and one name is as good as any *g*

Am working on my diploma thesis and in order to implement my code into
this big project, it seems I need to debug the whole project :(

Regards,

Lars

Aug 1 '06 #3
la**********@rw th-aachen.de wrote:
Victor Bazarov schrieb:
>la**********@rw th-aachen.de wrote:
>>private:
static char * myString;
Do the contents of this "string" ever change? No, I don't mean the
value of the pointer, I mean, do you ever change individual chars in
this "string"? If not, it should be declared a pointer to const
char:

Don't change, but it's pretty irrelevant because I was simplifying for
the example. The real code here uses lots of pointers to changing data
as member variables of class "foo".
>>>From my understanding of C, the line
myString = (char *) someString;
stores a copy of the pointer to the parameter
No. It "stores a copy of the pointer". Not "to the parameter".

Still unclear. Given someString points to memory address X, then
after the assignment of myString, myString also points to memory
address X, right? That's what I meant.
Then you're correct. The copy of the pointer value is created.
>>myString, which can cause undefined behaviour, because the parameter
string is a (const char *) and loses validity after the function
exits.
No, it does not. The value does not lose validity.

Oh okay - I didn't know that. So if you store a pointer to a
const char passed to a function, the memory reserved for the
string during the function call stays untouched?
Well, it's so with a literal. Generally speaking (to complicate things)
it is possible that the memory will go away. Inside the function we
don't know how the address passed to the function was obtained. But
it definitely does not lose validity (in your case) until the end of
the function, and if it's the address of the literal, it stays OK.
>>Question no. 2: Is the usage of classes without an instance
excusable under ANY circumstances?
Sure.
Mkay...
>Static data members are singletons. If the program design calls for
a singleton, use it.

Thanks for the keyword...
http://en.wikipedia.org/wiki/Singleton_pattern
cleared up a few of my questions about how it is designed in this code
here. According to wiki, the constructor should be made either private
or protected, is NO constructor achieving the same effect? This class
has none.
But this class is not a singleton. Each of the static data members is.
And then, again, don't look at the pattern (yet). If you need some kind
of a C string and it has its designated purpose, and there is no need to
have many of them, then a static data member of some class will do.
For debugging purposes, I made it a normal class now and am using only
1 instance of it.
That's up to you, of course. I was using the word 'singleton' to mean
that there is only one of something, not to refer to the pattern.
>There is no need - objects with static duration are created at the
start of the program and disposed of at the end of the program. If
the type of a static object has a constructor, it will be called,
same for the destructor. In your example, the static objects are of
the built-in types, no constructor or destructor exists.

Hmm... so that means when the program exits - using exit (0); -
mtrace would NOT detect a memory leak unless there is some bug in the
code?
I don't know what you're talking about.
>WHY? What for? Does the program work? If it ain't broke, don't
fix it.
Nope - program has some huge memory leaks - over 200 megabytes of log
file from mtrace(). I am trying to fix them one by one, so I'm
changing everything that mtrace identifies as memory leak when I do a
chain of return; - at any point in the program to exit to the main
routine and then exit the
application.
That's a good approach. I didn't see any memory leaks in the code you
posted, though.
The memory leaks make the code behave unpredictable and the behaviour
changes even on introduction of cerr-statements.
That can be also due to malformed code produced by the optimizing
compiler.
>BTW, what book on C++ are you currently reading?
None, I just used the "foo" term because I saw it in lots of examples
and one name is as good as any *g*

Am working on my diploma thesis and in order to implement my code into
this big project, it seems I need to debug the whole project :(
Well, good luck with it! Ask more questions as you need. We're here to
help.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 2 '06 #4

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

Similar topics

28
20301
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()', this.pinginterval); - but is there no way to do this without using the literal ObjectName? If I write 'this.methodName()' I get "Line 1 Char 1: Object doesn't support this property or method." in IE, and nothing happens in Firebird.
3
5287
by: simon lee | last post by:
Dear all, I have a html code like <a href="product.html" target=new>product</a> Although the file "product.html" can be opened at the new page, but with scrollbar, menu, location, and so on, please help me to write the javascript code or others in order to remove all such features when open this page, thanks.
26
448
by: codymanix | last post by:
Last night I had several thought about RAII and want to discuss a bit. Why doesn't CSharp support destructors in structs? Wouldn't that make RAII possible like in C++? When the struct goes out of scope, the dtor could be immediately be called (no GC needed). For that, you don't have to declare the whole File class as a struct (which would be not good for performance when File has a lot of data-members). Instead creating a thin wrapper...
6
15207
by: marktm | last post by:
Hi- I am trying to use setInterval to call a method within an object and have not had any luck. I get "Object doesn't support this property or method" when I execute the following code. What I am doing wrong? Your help will be much appreciated. Thanks
14
11072
by: D. Alvarado | last post by:
Hello, I am trying to open a window containing an image and I would like the image to be flush against the window -- i.e. have no padding or border. Can I make this happen with a single call to a window.open function? I would prefer not to create a separate HTML page. So far all I have is the basic var cwin = window.open('images/KJV-THANKS.gif', 'Thanks', 'width=243,height=420,'); cwin.focus();
121
10023
by: typingcat | last post by:
First of all, I'm an Asian and I need to input Japanese, Korean and so on. I've tried many PHP IDEs today, but almost non of them supported Unicode (UTF-8) file. I've found that the only Unicode support IDEs are DreamWeaver 8 and Zend PHP Studio. DreamWeaver provides full support for Unicode. However, DreamWeaver is a web editor rather than a PHP IDE. It only supports basic IntelliSense (or code completion) and doesn't have anything...
19
676
by: Kamilche | last post by:
I have looked at many object-oriented programming frameworks out there for C. Though the ideas presented are intriguing, and I've used some of them in my own work, they all suffered some drawback or another. I have created a new method of doing OOP with C, something that fits my needs particularly well. I haven't encountered anything else like it, so I'm tossing it out to the Internet for comment. ...
1
11128
by: Screenbert | last post by:
After finding nothing anywhere in google I am posting this so everyone can benefit by it. The formating is not pretty since I copied it from my word document, but you should benefit by it. Managing DHCP Servers using C# They said it was impossible. It couldn't be done. But you can in fact manage DHCP servers using C#. This includes creating and deleting Scopes, SuperScopes, Reservations, Exclusions, Options and so forth. Since the dll...
0
12349
by: screenbert | last post by:
Managing DHCP Servers using C# They said it was impossible. It couldn't be done. But you can in fact manage DHCP servers using C#. This includes creating and deleting Scopes, SuperScopes, Reservations, Exclusions, Options and so forth. Since the dll that is used was written several years ago by Microsoft, you cannot manage things on the DNS tab when looking at a reservation and few things such as that however it gives you main things you...
0
8375
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
8290
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
8815
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
8707
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
8482
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,...
1
6161
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
4294
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1593
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.