I’m trying to do something like this in my Obj class:
public:
template <typename T>
Obj(T & o) {
siz = sizeof(o);
p = malloc(siz);
memcpy(p, &o, siz);
}
private:
void * p;
size_t siz;
That works fine if i do something like this:
string str = "foobar";
Obj u = Obj(str);
but not if I do something like this:
Obj u = Obj(string("foobar"));
That results in a string filled with random characters.
To retreive the string I use:
string S() {
return *((string *)p);
}
Any idea?
As others have commented you should not be doing something like this. The code example you have given will not work for anything that is not a POD (http://stackoverflow.com/questions/146452/what-are-pod-types-in-c). When you do the memcpy you may not be initializing the new object correctly. E.g. if it has members that are pointers. In the case of the string its implementation likely holds a pointer to a character buffer that is owned by the original string. When the original string gets deleted, the character buffer will too. But your memcopied object will still point to the deleted buffer.