473,520 Members | 2,635 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Setting every bit in all members of a class to 0

Hello everyone,

Consider a class with many integer members.
I want to set every bit in all members to 0 in the constructor.

struct Foo
{
Foo() { memset(this, 0, sizeof *this); }
int a, b, c, d, e, f, g, h, i, j, k;
};

Is it safe to use memset this way in this situation?

Regards.
Mar 23 '07 #1
6 5004
On 23 Mar, 10:36, Spoon <devn...@localhost.comwrote:
Hello everyone,

Consider a class with many integer members.
I want to set every bit in all members to 0 in the constructor.

struct Foo
{
Foo() { memset(this, 0, sizeof *this); }
int a, b, c, d, e, f, g, h, i, j, k;

};

Is it safe to use memset this way in this situation?
Perhaps in this case, but in general no. If you have members of non-
POD types you can get a lot of problems.

--
Erik Wikström

Mar 23 '07 #2
On Mar 23, 10:36 am, Spoon <devn...@localhost.comwrote:
Hello everyone,
Hello,
>
Consider a class with many integer members.
I want to set every bit in all members to 0 in the constructor.

struct Foo
{
Foo() { memset(this, 0, sizeof *this); }
int a, b, c, d, e, f, g, h, i, j, k;

};

Is it safe to use memset this way in this situation?
I don't see any argument not to do so...
>
Regards.
Regards

Mar 23 '07 #3
"Spoon" <de*****@localhost.comwrote in message
news:46**********************@news.free.fr...
: Consider a class with many integer members.
: I want to set every bit in all members to 0 in the constructor.
:
: struct Foo
: {
: Foo() { memset(this, 0, sizeof *this); }
: int a, b, c, d, e, f, g, h, i, j, k;
: };
:
: Is it safe to use memset this way in this situation?

Formally, this triggers undefined behavior according to
the C++ standard - unfortunately.
It is illegal to "overwrite" a non-POD type using memset,
and having a constructor means that Foo is not POD.
There are proposals for C++0x to formally allow this
(by making sub-categories of "POD" types).

In practice, it is likely to behave as expected in this
simple case (memset would obviously be bad if Foo had
a virtual member, or a base class with such a member).

Unfortunately, in the constructor, there is no simple
and portable way to automatically initialize members of
built-in types to a default value. I am not aware of any
formally portable shortcut to avoid the error-prone
listing of every member in the initialization-list:
Foo():a(0),b(0),c(0),d(0),e(0),f(0),g(0),h(0),i(0) ,j(0),k(0){}

However, some compilers or source-checking tools may
provide warnings if only a subset of members is listed
in an initialization-list.
I hope this helps,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form

Mar 23 '07 #4
* Ivan Vecerina:
"Spoon" <de*****@localhost.comwrote in message
news:46**********************@news.free.fr...
: Consider a class with many integer members.
: I want to set every bit in all members to 0 in the constructor.
:
: struct Foo
: {
: Foo() { memset(this, 0, sizeof *this); }
: int a, b, c, d, e, f, g, h, i, j, k;
: };
:
: Is it safe to use memset this way in this situation?

Formally, this triggers undefined behavior according to
the C++ standard - unfortunately.
It is illegal to "overwrite" a non-POD type using memset,
and having a constructor means that Foo is not POD.
There are proposals for C++0x to formally allow this
(by making sub-categories of "POD" types).

In practice, it is likely to behave as expected in this
simple case (memset would obviously be bad if Foo had
a virtual member, or a base class with such a member).

Unfortunately, in the constructor, there is no simple
and portable way to automatically initialize members of
built-in types to a default value. I am not aware of any
formally portable shortcut to avoid the error-prone
listing of every member in the initialization-list:
Foo():a(0),b(0),c(0),d(0),e(0),f(0),g(0),h(0),i(0) ,j(0),k(0){}

struct FooPOD { int a, b, c, d, e, f, g, h, i j k; };
struct Foo: FooPOD { Foo(): FooPOD() {} };
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Mar 23 '07 #5
"Spoon" <de*****@localhost.comwrote in message
news:46**********************@news.free.fr...
Hello everyone,

Consider a class with many integer members.
I want to set every bit in all members to 0 in the constructor.

struct Foo
{
Foo() { memset(this, 0, sizeof *this); }
int a, b, c, d, e, f, g, h, i, j, k;
};

Is it safe to use memset this way in this situation?
This was done quite a bit in C. I was working on some code in C converting
it to C++. One thing I wanted to do was to add a class with a constructor
to structure. Which broke. And I couldn't figure out why. Then I finally
tracked it down to a memset type of issue( it was different, but similar).

Consdier you class.

struct Foo
{
Foo() { memset( this, 0, sizeof *this ); }
int a,b,c,de,f,g,j,i,j,k;
};

Later you decide to store a name in this so you add a std::string.

struct Foo
{
Foo() { memset( this, 0, sizeof *this ); }
int a,b,c,de,f,g,j,i,j,k;
std::string Name;
};

Now Name won't work. It'll cause memory segmentation faults and such when
you try to access it. Can you figure out why? Because all the ponters
stored in Name when it has been constructed have been set to 0, effectively
becoming NULL pointers (on some systems) losing the memory they pointed to,
along with other data they need.

memset of a structure or class is a BAD thing.
Mar 23 '07 #6
ldh
I am not aware of any
formally portable shortcut to avoid the error-prone
listing of every member in the initialization-list:
Foo():a(0),b(0),c(0),d(0),e(0),f(0),g(0),h(0),i(0) ,j(0),k(0){}
A little class like this one can be useful for classes where this is
an issue:

//auto-initialize POD types as well as class types
template<typename T>
struct auto_zero {
T data;
operator T&() {return data;}
operator T const&() const {return data;}

auto_zero(T const& d) : data(d) {}
auto_zero() : data() {}
};

This is probably fairly similar to boost::value_initialized also. I've
sometimes also found it convenient to partially specialize for
pointers:

template<typename T>
struct auto_zero<T*> {
T* data;
operator T*&() {return data;}
operator T* const&() const {return data;}

T& operator*() const {return *data;}
T* operator->() const {return data;}

auto_zero(T *const d) : data(d) {}
auto_zero() : data() {}
};

Anyway the idea is, instead of

struct A {
int i,j,k,l,m;
A() : i(), j(), k(), l(), m() {}
};

which can easily become a maintenance problem, you just do

struct A {
auto_zero<inti,j,k,l,m;
};

The automatic conversions make this completely transparent pretty much
99% of the time, occasionally you need an explicit cast, such as if
you want to use one of the variables in a switch statement.

-Lewis

Mar 23 '07 #7

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

Similar topics

5
451
by: Andre | last post by:
I have two questions; 1) When executing the sub routine "TestStructure", I'm trying to update the member "intTyres" in the structure "structureCar" dynamically using System.Reflection. The code executes, but the value does not change, nor is there an exception thrown. 2) Read comments in sub routine "TestIntegerProperty"
0
1568
by: Cat | last post by:
I have class Base, and class Derived. I am serializing Derived objects from XML, and these Derived objects are allowed to 'inherit' the values from other named Base objects already defined in the XML. <Base name="cat"/> <Derived name="tabby" inherits="cat"/> Some Derived objects are not fully described in the XML, and their members
1
2575
by: Greg Hurlman | last post by:
I have an HttpModule that captures the FormsAuthenticationModule.Authenticate event, and replaces the HttpContext principal with a custom principal. The code is straightforward enough, yet when an ASPX page tries to get this custom principal it fails - the object I inserted is not there. I've tried having this module declaration at both the...
1
6446
by: laredotornado | last post by:
Hi, I'm using PHP 4.4.4 on Apache 2 on Fedora Core 5. PHP was installed using Apache's apxs and the php library was installed to /usr/local/php. However, when I set my "error_reporting" setting to be "E_ALL", notices are still not getting reported. The perms on my file are 664, with owner root and group root. The php.ini file is located...
2
1569
by: Avinash | last post by:
I have a class defined as follows: class main { ........ protected: another_class *obj; public: void set_another_class(another_class *ptr);
41
2826
by: Jim | last post by:
Hi guys, I have an object which represents an "item" in a CMS "component" where an "item" in the most basic form just a field, and a "component" is effectively a table. "item" objects can be created and then added to "component" objects to build up the component definition. My dilemma comes in deciding how to read/write data to the...
8
4415
by: Michael Howes | last post by:
I have some code that manages local user logins. When I create a new user I want to set the password to expire every x days and the number of failed login attempts before the account is disable/locked out. I can't seem to figure out how. I saw two properties in MSDN BadPasswordAttempts and MaxPasswordAge but I can't seem to set them on the...
1
274
by: Michael Bell | last post by:
Newbie here! Asking more innocent and low-level questions. I am working my way through text-books which say different things. Or maybe they come to the same thing. Ah, that's life! Are these two ways of declaring a class and its instances (also called "members"?) are equally correct?
8
1885
by: Jonathan Wood | last post by:
I want to dynamically set my site's theme based on a setting stored in my database. I just hooked this up but get an error that the theme can only be set in the page's PreInit event or earlier. However, it appears that Master pages do not have PreInit events. I REALLY do not want to have to stick the same code in each and every page I...
0
7299
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...
0
7201
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...
0
7602
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...
1
7163
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...
0
7559
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...
1
5125
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...
0
1646
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
1
836
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
506
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...

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.