1
class SomeClass
{
public:
    int SomeFunc();
    virtual void DoSomeThing();
    void Copy(MyContainer* container)
    {
        //Is this line OK?
        //why not memcpy(container->data, this, sizeof(SomeClass) ?
        memcpy(&container->data, this, sizeof(SomeClass));
    }

    SomeClass* GetFromCopy(MyContainer* container)
    {
        //And this ?
        return (KLunaBase*)&container->pData;
    }

    void Test()
    {
        MyContainer* cont = NULL;
        container = malloc(sizeof(cont) - sizeof(cont->data) + size);
        Copy(cont);
    }

private:
    int a;
    int b;
    SomeOtherClass objA;
}

struct MyContainer
{
    const void* data;
}

I have read some historic code, which simplified above, the function Copy and GetFromCopy I could not understand. I know that POD class can copy, but what if the class have virtual function and reference member object ?

sorry for my poor English.

Liu Hao
  • 472
  • 4
  • 24
  • 8
    **NO**, no, definitely not. – StoryTeller - Unslander Monica Oct 02 '17 at 12:26
  • related/dupe: [1](https://stackoverflow.com/questions/26227965/memcpy-a-non-pod-object), [2](https://stackoverflow.com/questions/29167512/why-cant-non-pod-objects-be-copied-with-memcpy), [3](https://stackoverflow.com/questions/17810174/why-isnt-memcpy-guaranteed-to-be-safe-for-non-pod-types) – NathanOliver Oct 02 '17 at 12:27
  • 3
    WARNING: The answers to the duplicate question are at best unhelpful and at worst misleading. If `SomeClass` is trivially copy-able the compiler implemented copy constructor will work that way anyway. There are clever tricks copying arrays as a block using `memcpy` but the answer is "use `std::vector` which will do that where valid (and better in move cases)". Use the type-system and templates properly and all these decisions will be made efficiently for you. – Persixty Oct 02 '17 at 12:50
  • 1
    Also, why are you using `malloc`? That is the other issue that you missed. All `malloc` does is allocate memory -- it does not create objects. Stop mixing C way of doing things with C++. – PaulMcKenzie Oct 02 '17 at 12:56

1 Answers1

2

No, don't do that.

Provide a proper copy constructor and assignment operator instead, respectively use the compiler generated ones.

user0042
  • 7,917
  • 3
  • 24
  • 39