Re: Question about compiler bug: Value-initialization in new-expression
So VC++ does not support value-initialization correctly for types like
the struct A, from
connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100744:
struct A {
std::string s;
int i;
};
As a workaround, Carl Daniel [VC++ MVP] suggested adding a constructor
to A:
struct A {
std::string s;
int i;
A() : i(0) {}
};
This will indeed fix the initialization, e.g., when doing "new A()".
However, there are a number of problems to this approach:
- It might not be allowed to modify A, e.g., because it might be part of
a third party library.
- Adding a constructor to struct A would break code that used to be
valid, e.g.:
A a = { "some text", 66 };
- It would create an extra maintenance burden. If data members would be
added later, the constructor would possibly need to get updated as well,
which is tedious and error prone. For example:
struct A {
std::string s;
int i;
char c;
int *p;
double d;
A() : i(0), c('\0'), p(NULL), d(0.0) {}
};
Actually I originally chose to put my data members into a struct because
I expected them to be initialized very easily, without needing to put
them into a member initializer list! I got this idea from a posting by
Andrew Koenig, at comp.lang.c++.moderated (Re: zero initialize a large
amount of class members):
class Large { struct Initialized { int a; int b; // and so on } m;
Large(): m(Initialized()) { /* ... */ } };
Now if you add a new member to struct Initialized, it will
automatically start out as zero
It's often very important to have our data properly initialized. So
hopefully the status of bug report 100744 is going to be reconsidered
soon!
Kind regards, Niels