Workaround for compiler bug: Value-initialization in new-expression
Carl Daniel [VC++ MVP] wrote:
Niels Dekker - no return address wrote:
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!
I don't want to crush your hopes, but realistically, unless this is a
serious issue for you that you persue through PSS, it's unlikely that
a fix will be made in the next 2 years or more
I just thought of another workaround... Again, suppose that struct A is
defined as in
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100744
struct A {
std::string s;
int i;
};
Now it was reported that VC++ does not properly initialize A::i when
doing:
A *pa = new A();
So instead I made a class GetInitializedAggregate, so that the following
will do the job:
A *pa = new A( GetInitializedAggregate() );
The class GetInitializedAggregate is implemented as follows:
class GetInitializedAggregate {
public:
template <typename T> operator T() const {
T result = {};
return result;
}
};
The conversion operator T() returns a properly initialized object, for
any aggregate type T. In that way, the expression
GetInitializedAggregate() "automagically" delivers an initialized
aggregate of the right type. :-)
Any comments, please? Is this technique presented elsewhere already?
--
Niels Dekker
http://www.xs4all.nl/~nd/dekkerware
Scientific programmer at LKEB, Leiden University Medical Center