memset structure with std::string contained
No, you cant, it would overwrite the internal state of the string and make bad things happen. You could wrap all the POD stuff in a seperate struct and put that in your current one, that way you could memset that and let the string default construct.
Edit: Just to clarify, the string will almost certainly be storing a pointer to the memory its allocated for storage. The string's constructor will always have run before you can memset it (even if you memset this
in the constructor of your type, the string constructor would run first). So you would be overwriting this pointer value, and instead of pointing to its storage, it would a pointer to NULL, or some other almost definitely invalid value.
Here's an exotic idea: Suppose your class Foo
has lots of primitive members which remain uninitialized in Foo
's constructor, with the exception of one string:
class Foo
{
int a;
double b;
std::string s;
};
The constructor Foo::Foo()
will correctly initialize the string, but it won't care for anything else. So, let's zero out the memory before we construct!
void * addr = ::operator new(sizeof(Foo));
std::memset(addr, 0, sizeof(Foo));
Foo * p = new (addr) Foo;
// later
p->~Foo();
::operator delete(addr);
Of course it would be cleaner to just initialize all the members to zero in the constructor, but perhaps you have your own reasons that you don't want to create a custom constructor.