PAGE2GO2 HOME | INTERNET NEWS

LeighExchange - Free Advertising Network Stock Research at Internet Speed Need Money Easy and Quick?

Re: Setting every bit in all members of a class to 0

 List
Subject: Re: Setting every bit in all members of a class to 0
Poster: ldh
Date: 23 Mar 2007 14:16:36 -0700
Related Postings: 1 2 3 4 5 6

> 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 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 struct auto_zero { 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 i,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

 

Page2Go2.com is not responsible for content of this message.