Reputation: 5069
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?
Upvotes: 2
Views: 10094
Reputation: 49976
strMyStruct x1;
here x1.s1
is correctly constructed with empty string.
memset(&x1, 0, sizeof(x1));
at this place you have overwritten internal fields of x1.s1
- most probably seting to null pointer which was holding string buffer - but it depends on its implementation. You should be aware that using memset in such way is Undefined Behaviour - mostly casing crashes. But crash willnot happen here, at least yet.
x1.a = 100
thats fine
x1.s1.append("....");
and now you try to use x1.s1 which is in undefined state, this most probably will crash because internal data (pointer to memory buffer) is null. But you dont now, this might work - it depends on string implementation.
Finally your code can crash when x1.s1 will get destroyed.
You cannot use memset on non POD structures, and your struct is not such struct. So you are left with either using constructor for initializing your data, or universal initialization as in @CoryCramer answer.
Upvotes: 3
Reputation: 117856
You can use uniform initialization to default construct the object.
strMyStruct x1{};
This will default initialize the members of that object. The way you have it written, the variable is declared but not initialized. You can also use this syntax to value initialize your struct.
strMyStruct x2{5, "foo", "bar"};
Upvotes: 7