0

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?

David G
  • 94,763
  • 41
  • 167
  • 253
Luke Givens
  • 829
  • 1
  • 11
  • 15
  • 4
    _I'm trying to do something like this_ Why are you trying to do it this way? Whatever it is you are trying to do, there is probably a better way. – James McNellis Sep 26 '12 at 22:22
  • Every line of this code looks like a horrible nightmare. What are you *really* trying to achieve? – Kerrek SB Sep 26 '12 at 22:26
  • tip: memcpy does not belong in C++ code – Mooing Duck Sep 26 '12 at 22:31
  • Nor does `malloc`. Also storing things as `void *` is a bad idea. Lose the ability for the compiler to make things type safe. – Ed Heal Sep 26 '12 at 23:05
  • This is indeed an abomination, @EdHeal, for both type-safety and the assumption T has no identity. I can have two 5s and they are the same, but they are each a different 5 @ op – Alec Teal Nov 30 '13 at 00:02

2 Answers2

2

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.

combinatorial
  • 9,132
  • 4
  • 40
  • 58
1

Well, it's extremely hard to guess what you are trying to do.

What you seem to be doing is making a binary copy of an object, which is a severe case of everything that is bad and evil. In your first case, you are doing this to a "real" object, so it might appear to work since the original object (the str object) is still around, so whatever pointer the copy contains still points to 'valid' data. In the second case, you are doing it to a temporary object which gets deallocated right after the thing, which is probably why your "copy" only has garbage.

Either way, from the looks of it, neither of the two actually do anything reaosnable at all. I'd say that your first example only appears to work.

Christian Stieber
  • 9,954
  • 24
  • 23