I have a struct that looks like this:
typedef struct {
int a;
//other fields
string s1;
string s2;
} strMyStruct;
In The following code, append() method will crash since the string object x1.s1 was not constructed.
strMyStruct x1;
memset(&x1, 0, sizeof(x1));
x1.a = 100
x1.s1.append("....");
I can do placement new to solve it like new (x1.s1) string;, but it's too cumbersome and I don't have total control on the structure of strMyStruct: someone may add another string as a field to this struct and start using it and hit the crash issue, until he remembers to do placement new trick.
Really hoping the string class can handle it properly when initialization is done by memset(&x1, 0, sizeof(x1));. Is there a trick on this?
memset? Why not use a normal constructor? The linestrMyStruct x1;is already initializing the strings.typedefastructin C++ (structnames are automatically a typename). Difference between 'struct' and 'typedef struct' in C++?memset()to initialize complex objects :-P ...but it was acceptable beforeIt should never have been acceptable, regardless of the member types in the struct. In C++, always use proper C++ initialization techniques, even if the struct or class contains POD (simple) types as members.