473,769 Members | 2,222 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Clearing structures with member functions.

I ran across some code that called memset(this, 0, sizeof(*this)) in
the member function of a structure in C++. This just looked wrong to
me so I did some web searching and it does indeed seem like a
questionable thing to do. Looking around further took me to a
newsgroup discussion that said the better approach was to do something
like sv = Struct(). The thing is that both cases seem to bo "ok" so
long as there are no virtual functions and no constructor in Struct or
any of its internals. Code like this does not initialize the object to
0:

struct SOut {
int x;
struct SIn {
int y;
SIn : y() {} // or this could be a virtual function...
} in;
}

....

SOut out = SOut(); // initializes y but not x.

out = SOut(); // clears y but not x...

So, since using either approach breaks if given certain circumstances
the question of which is more correct seems unclear. Since this is a
performance issue the real question is which is the faster, memset(x,
0, sizeof(x)) or x = X()? Another question is if the above code should
be clearing the value of x...so long as SIn has no constructor or
virtual functions it works, but as soon as it does the default
constructor of SOut no longer clears x. What law in C++ governs this
behavior?

Is using memset immoral even if you KNOW that the object will never
have any virts? The only reason why I would think it might be is that
these structs have member functions...and calling memset on this
/seems/ icky. I can definately see an argument comming over this and I
would like to be sure of my position...and IANAL.

Thanks.

Nov 22 '05 #1
15 2078
ro**********@gm ail.com wrote:
struct SOut {
int x;
struct SIn {
int y;
SIn : y() {} // or this could be a virtual function...
} in;
}


Why not just generate a constructor for SOut then and avoid memset all
together?

-Josh McFarlane

Nov 22 '05 #2

<ro**********@g mail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
I ran across some code that called memset(this, 0, sizeof(*this)) in
the member function of a structure in C++. This just looked wrong to
me so I did some web searching and it does indeed seem like a
questionable thing to do. Looking around further took me to a
newsgroup discussion that said the better approach was to do something
like sv = Struct(). The thing is that both cases seem to bo "ok" so
long as there are no virtual functions and no constructor in Struct or
any of its internals. Code like this does not initialize the object to
0:
And no pointer or floating point members. All-bits-zero is
not guaranteed to evaluate to NULL or 0.0

struct SOut {
int x;
struct SIn {
int y;
SIn : y() {} // or this could be a virtual function...
} in;
}

...

SOut out = SOut(); // initializes y but not x.

out = SOut(); // clears y but not x...

So, since using either approach breaks if given certain circumstances
the question of which is more correct seems unclear. Since this is a
performance issue

Are you sure? Have you proven so with valid measurements?
the real question is which is the faster, memset(x,
0, sizeof(x)) or x = X()?
One of them. Either of them. Neither of them. THe language
says nothing about performance (other than the standard library
'big-O' specs).
Another question is if the above code should
be clearing the value of x...so long as SIn has no constructor or
virtual functions it works, but as soon as it does the default
constructor of SOut no longer clears x. What law in C++ governs this
behavior?
I'll let someone else look that up, and at the same time advise
against using memset in that context.

Is using memset immoral even if you KNOW that the object will never
have any virts? The only reason why I would think it might be is that
these structs have member functions...and calling memset on this
/seems/ icky.
IMO not just 'icky', but a dangerous practice.
I can definately see an argument comming over this and I
would like to be sure of my position...and IANAL.

Thanks.


I think a better question is why is there a need to 'zero-out' all
a class' data members in one sweep? IMO each data member has a specific
meaning and purpose, along with function(s) to manipulate it. If in the
course of processing, one or more data members need to be 'reset',
this should be done in that logic, unambiguously, e.g.

{
/* etc */
x.a = 0;
x.b = 0;
/* etc */
}

Many programmers think they can optimize code by hand better than
their compiler can. They're almost always wrong.

-Mike
Nov 22 '05 #3

Mike Wahler wrote:
<ro**********@g mail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
I ran across some code that called memset(this, 0, sizeof(*this)) in
the member function of a structure in C++. This just looked wrong to
me so I did some web searching and it does indeed seem like a
questionable thing to do. Looking around further took me to a
newsgroup discussion that said the better approach was to do something
like sv = Struct(). The thing is that both cases seem to bo "ok" so
long as there are no virtual functions and no constructor in Struct or
any of its internals. Code like this does not initialize the object to
0:
And no pointer or floating point members. All-bits-zero is
not guaranteed to evaluate to NULL or 0.0


We are not concerned with the behavior of some obscure, non-existant
implementation in which NULL is not 0. In practice I have never seen
such a thing occur. As the compiler, hardware, OS, and all that is
known _I_ can guarantee that all bits zero is null and 0.0.

If I am to convince others that we need to change this practice I can't
make such arguments my sole point as for us and our targets they are
moot. Performance is given precidence over standards compliance here
so unless there is some *practical* reason the practice won't change.
If there is a piece of hardware out there that uses something other
than 0 to mean 0.0 or null then MAYBE, but afaik no such thing exists
and the x86 running Windows is certainly not one of them.

I agree that depending on an implementation is bad form, but I am
working in a Windows house and that is just plain the norm under such
situations. My OS, hardware, and compiler are not likely to change in
such a manner and nobody is concerned with compatibility with something
obscure or theoretical.
the real question is which is the faster, memset(x,
0, sizeof(x)) or x = X()?


One of them. Either of them. Neither of them. THe language
says nothing about performance (other than the standard library
'big-O' specs).


I was hoping for a practical answer.
I think a better question is why is there a need to 'zero-out' all
a class' data members in one sweep?


Note that I did specify structure and not class.

Nov 22 '05 #4
ro**********@gm ail.com wrote:

Note that I did specify structure and not class.


So? The *ONLY* difference between a struct and a class is the default
access (struct => public, class => private).

A class can be a POD, a struct can be a non-POD. The key thing is that
while memset(this,0,s izeof(*this)) may be OK in certain circumstances on
a POD, using it leads to bad habits. And if it changes so that your
struct is no longer a POD, but has virtual functions, for example,
congrats! You just clobbered your VPTR.

Instead, you should create a constructor for your POD class

struct X {
int x;
int y;
X(int x_ = 0, int y_ = 0) : x(x_), y(y_) { }
};
Nov 22 '05 #5

roberts.n...@gm ail.com wrote:
Is using memset immoral even if you KNOW that the object will never
have any virts? The only reason why I would think it might be is that
these structs have member functions...and calling memset on this
/seems/ icky. I can definately see an argument comming over this and I
would like to be sure of my position...and IANAL.


I can make my question clearer:

Assuming I have a Struct variable "s" that contains member functions,
which is the better way to clear its values and why?

1 - memset(&s, 0, sizeof(s));
2 - s = Struct();

If 1, is doing that from inside the structure really a big deal or is
it something that can be depended upon to work given that Struct will
never have virtual members?

Nov 22 '05 #6
ro**********@gm ail.com wrote in
news:11******** **************@ o13g2000cwo.goo glegroups.com:

Mike Wahler wrote:
<ro**********@g mail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
>I ran across some code that called memset(this, 0, sizeof(*this)) in
> the member function of a structure in C++. This just looked wrong
> to me so I did some web searching and it does indeed seem like a
> questionable thing to do. Looking around further took me to a
> newsgroup discussion that said the better approach was to do
> something like sv = Struct(). The thing is that both cases seem to
> bo "ok" so long as there are no virtual functions and no
> constructor in Struct or any of its internals. Code like this does
> not initialize the object to 0:
And no pointer or floating point members. All-bits-zero is
not guaranteed to evaluate to NULL or 0.0


We are not concerned with the behavior of some obscure, non-existant
implementation in which NULL is not 0. In practice I have never seen
such a thing occur. As the compiler, hardware, OS, and all that is
known _I_ can guarantee that all bits zero is null and 0.0.


However... you're posting in comp.lang.c++. We're platform agnostic over
here. All we get to assume is the Standard. How a particular
implementation behaves belongs in a newsgroup dedicated to that platform.
If I am to convince others that we need to change this practice I
can't make such arguments my sole point as for us and our targets they
are moot. Performance is given precidence over standards compliance
here so unless there is some *practical* reason the practice won't
change. If there is a piece of hardware out there that uses something
other than 0 to mean 0.0 or null then MAYBE, but afaik no such thing
exists and the x86 running Windows is certainly not one of them.
Nor should you. However, you are posting in comp.lang.c++ where we don't
get to assume platform-specific behaviours. And whatever we do say that
works, will work on _any_ platform (assuming the usual things, like a
Standards-compliant compiler... a well-formed program that doesn't
exhibit Undefined Behaviour, etc...).
I agree that depending on an implementation is bad form, but I am
working in a Windows house and that is just plain the norm under such
situations. My OS, hardware, and compiler are not likely to change in
such a manner and nobody is concerned with compatibility with
something obscure or theoretical.


That's nice... but doesn't belong in comp.lang.c++.
> the real question is which is the faster, memset(x,
> 0, sizeof(x)) or x = X()?


One of them. Either of them. Neither of them. THe language
says nothing about performance (other than the standard library
'big-O' specs).


I was hoping for a practical answer.


That would be platform-specific (and potentially implementation-
specific), and thus belongs in a newsgroup dedicated to your platform
and/or specific compiler.
Nov 22 '05 #7

<ro**********@g mail.com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .

roberts.n...@gm ail.com wrote:
Is using memset immoral even if you KNOW that the object will never
have any virts? The only reason why I would think it might be is that
these structs have member functions...and calling memset on this
/seems/ icky. I can definately see an argument comming over this and I
would like to be sure of my position...and IANAL.


I can make my question clearer:

Assuming I have a Struct variable "s" that contains member functions,
which is the better way to clear its values and why?

1 - memset(&s, 0, sizeof(s));
2 - s = Struct();

If 1, is doing that from inside the structure really a big deal or is
it something that can be depended upon to work given that Struct will
never have virtual members?


In the current issue of C/C++ User's Journal, Koenig and Moo have an article
warning against violating abstractions. They also make the case that even
the simplest struct represents some level of abstraction unless it is
comprised of nothing but public data. I suggest you invest in a copy. (The
short form is that violating abstractions makes the code less maintainable
and less portable.)

--
Cy
http://home.rochester.rr.com/cyhome/
Nov 22 '05 #8

<ro**********@g mail.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
I ran across some code that called memset(this, 0, sizeof(*this)) in
the member function of a structure in C++. This just looked wrong to
me so I did some web searching and it does indeed seem like a
questionable thing to do. Looking around further took me to a
newsgroup discussion that said the better approach was to do something
like sv = Struct(). The thing is that both cases seem to bo "ok" so
long as there are no virtual functions and no constructor in Struct or
any of its internals. Code like this does not initialize the object to
0:


All I can say was I was working on a program that was originally C. It did
the memset thing for it's structures and I didn't think much about it. I
made one of my own classes which initialized some data to certain values.
An existing structure was the best place to put this (which would then
really be a class but that's neither here nor there).

My code broke. Looking at my data I discovered that the variables I had
initialize in my class, which was inside the structure were 0, not the
values I initialized them to. So I had to get rid of the memset for this
structure, but it turned out that just about everything depended on the
variables being initialzed to 0.

So I then started making a constructor initializing the values to 0, and
soon discovered that this structure contained a lot more structures which
contained a lot more structures, etc... I wound up having to search out and
modify something like 15 structures and create constructors defaulting
values to zero just so I could put my class that needed to initialzied data
in the constructor inside this class.

It's not a good idea. Don't do it IMNSHO.
Nov 22 '05 #9
ro**********@gm ail.com wrote:
roberts.n...@gm ail.com wrote:
Is using memset immoral even if you KNOW that the object will never
have any virts? The only reason why I would think it might be is that
these structs have member functions...and calling memset on this
/seems/ icky. I can definately see an argument comming over this and I
would like to be sure of my position...and IANAL.


I can make my question clearer:

Assuming I have a Struct variable "s" that contains member functions,
which is the better way to clear its values and why?

1 - memset(&s, 0, sizeof(s));
2 - s = Struct();

If 1, is doing that from inside the structure really a big deal or is
it something that can be depended upon to work given that Struct will
never have virtual members?


Well it goes without saying that Struct will never have virtual methods
(that work) as long as there is code somewhere that is memsetting its
contents to 0. The problem with using memset in this way is that it
scatters such assumptions throughout the source code. In other words,
the definition of Struct does not express everything there is to know
about a Struct. Instead, the complete information can be found only by
examining every source file in the app, because the client has defined
the proper initialization state for a Struct.

In an object-oriented design, the object maintains its data, and
mediates both acccesses and changes to it. And the object itself
implements its initialization, not its clients. The benefits from doing
so are clear. Anyone wanting to find (or to change) how a Struct is
initialized, knows where to look for that code, and know also that it
is all in one place. The clients of Struct have a easier job as well. A
client no longer has to "know" that it's OK to call memset for a
Struct, but not, say, on a StructTwo. Such arbitrary knowledge does
nothing to produce better code, it simply makes it more difficult to
write correct code. And besides, how certain is it that Struct will be
a POD forever? How long does "never" usually last when it comes to
software design? Often not as long as one might expect - at least in my
experience.

Greg

Nov 23 '05 #10

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

Similar topics

11
2740
by: Fred Bennett | last post by:
I have a simulation project in which data can naturally be held in structures for processing. There are calls to multiple functions involved. Execution speed is an issue. Do I take a big hit for usuing structures? Is there a preferred way of passing the structures (or pointers?) that would speed up the program? I'm relatively new to C++. so, if you have time, detail (or references) would be appreciated. In any case any help is much...
4
3862
by: Thomas Paul Diffenbach | last post by:
Can anyone point me to an open source library of /statically allocated/ data structures? I'm writing some code that would benefit from trees, preferably self balancing, but on an embedded system that doesn't offer dynamic memory allocation (to be clear: no malloc, no realloc), and with rather tight memory constraints. Writing my own malloc to do dynamic allocation from some static pool isn't really an option, for various reasons, not...
6
390
by: Sam | last post by:
Hi everyone I'm confused by these declarations: struct hostent *he; server *s = (server*)malloc(sizeof(server)); /* in the code * he = gethostbyname(name);
6
2082
by: archilleswaterland | last post by:
structures typedef struct{ char name; int age; float balance; }account; account xyx; accout *ptr;
6
4488
by: Ken Allen | last post by:
OK, I admit that I have been programming since before C++ was invented, and I have developed more than my share of assembly language systems, and even contributed to operating system and compiler systems over the years. I have developed code in more than 30 distinct programming languages for a wide cariety of industries. But this issue of structures in C# is beginning to annoy me. I should also make it clear that I am not a big supporter...
12
2014
by: addinall | last post by:
Hi guys and gals, Haven't been in here for a good decade or so! I'm having a braid-dead moment that is lasting for a couple of days. Declaring pointers to functions witrhin structures and accessing same.... This doesnt work. I thought it should. The compiler disagrees with me! gcc32
44
5808
by: svata | last post by:
Hello, I wonder how to resize such array of structures using realloc()? #include <stdio.h> #include <stdlib.h> #define FIRST 7 typedef struct { char *name;
5
6609
by: Anan18 | last post by:
Hello sir, I'm supposed to Implement and Test the sequence Class Using a Fixed-Sized Array (Chapter 3), from Data Structures & Other objects using c++. The header file is provided, and so is a test program to check the correctness of the sequence class. I cannot figure out what the problem is and keep looking back and forth at the textbook and its not helping, can someone please please help me , i cannot figure out the errors in the...
3
1772
by: Martin | last post by:
Is clearing a structure the following way well defined in C89? The structure ACTION contains no floating point or pointer members. Only integral types. My thoughts concern the padding - can and should it be altered? typedef unsigned char Byte; #define MAX_ACTIONS 10 /* ... */
0
9590
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
9424
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
10223
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...
1
10000
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
8879
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
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...
2
3571
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.