-
Zero initialization of array members
Is this yet another behavior guaranteed by the language that I didn't know about?
In my case (g++ 3.something), using "()" on an array in a class constructor's initializer list ended up zeroing out all of the elements. Is this a language promise?
Code:
#include <iostream>
using namespace std;
struct B
{
int b;
int c;
};
class Test
{
public:
Test()
: a(), b()
{
cout << "a=" << a[0]
<< "," << a[1]
<< "," << a[2]
<< "," << a[3]
<< "," << a[4] << endl;
cout << "b=" << b[0].b
<< "," << b[1].b
<< "," << b[2].b
<< "," << b[3].b
<< "," << b[4].b << endl;
cout << "c=" << b[0].c
<< "," << b[1].c
<< "," << b[2].c
<< "," << b[3].c
<< "," << b[4].c << endl;
}
private:
int a[5];
B b[5];
};
int main()
{
Test t;
return 0;
}
printout:
a=0,0,0,0,0
b=0,0,0,0,0
c=0,0,0,0,0
-
It's tricky. Theoretically, the () in the mem-int list is interpreted as "default-initialize that member", and in this case, default initialization means zero initialization (as opposed to invoking the constructor, for an object with a non-trivial constructor). However, don't rely on this too much as not all compilers zero initialize a and b in this case.
It's similar to the difference between
Code:
struct B {int i;}; //POD type
B* p = new B(); //#1supposedly default initialization of B
as opposed to:
Code:
B* p = new B; //#2no initialization for B
A compliant compiler should zero initialize the B object in 1 but not in 2. Modern compilers do that but older ones don't so relying on zero initialization is not recommended, unless you know that the code will only be compiled with a fully-compliant compiler.
Last edited by Danny; 04-21-2010 at 03:13 PM.
Danny Kalev
Similar Threads
-
Replies: 26
Last Post: 12-01-2012, 04:12 AM
-
By Tmcclain in forum Java
Replies: 7
Last Post: 02-13-2009, 10:57 PM
-
Replies: 4
Last Post: 05-11-2008, 04:59 PM
-
Replies: 4
Last Post: 07-30-2007, 04:38 AM
-
Replies: 6
Last Post: 11-01-2005, 09:05 AM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks