-5

As i can understand,in c++, do memcpy with class object will require custom copy constructor defined to make operations like memcpy valid. Am i wrong? There is no virtual class method involved as well, like below:

class A {
 public:
   string name;
   int32_t score;
   A(const string &n, const int32_t score): name(n), score(score) {}
   A() {};
   ~A() {};
   // define custom copy constructor;
   A(const A &a) {
     name = a.name;
     score = a.score + 90;
   }
   A& operator=(const A &a) {
       name = a.name;
       score = a.score + 90;
       return *this;
   }
 };


int main() {
    cout << "test is running..." << endl;
    string name = "thisIsAName";
    A a(name, 66);
    A *a1 = new A();

    // send to another process
    produce(&a);
    // receive from the other process
    auto *res = consume();

    // cast to A
    if(res->size == sizeof(A)) {
        memcpy((uint64_t *)a1, (const uint64_t *)res->data, res->size;
    } else {
        // Do log error and return
        return 1;
    }

    std::cout << a1->name << "|" << a1->score << std::endl;
    std::cout << a.name << "|" << a.score << std::endl;

    cout << "test reached end" << endl;

    return 0;
}

Is there some mistake I made?

Also if possible please give a better understanding of memcpy in C++ with class object. Thank you very much.

++ Thank you guys, I just tested again seems i understood wrongly about memcpy and copy constructor. The reason to use memcpy to for casting to class A after receive an object from another process. So what's the best way to code in this situation? BR. Stefan

Stefan.L
  • 1
  • 1
  • 2
    Any reason not to just define a copy constructor to avoid using `memcpy`? also not sure why you're casting a `A*` to a `uint64_t*` – EdChum Jul 25 '17 at 13:44
  • 1
    That is all so wrong! You initialize `a` to point to a *string literal* (not an actual `A` object). You overwrite data with total disregard for copy-constructor or copy-assignment. – Some programmer dude Jul 25 '17 at 13:44
  • 1
    Your code is incomplete and the parts you posted are wrong. Please post real code. – Jabberwocky Jul 25 '17 at 13:44
  • 12
    Stop what you are doing. Take a deep breath. Pick a good [C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), and learn from it properly. Learning C++ by pure trial and error will only make things harder for you. – StoryTeller - Unslander Monica Jul 25 '17 at 13:44
  • 6
    Using `memcpy` with C++ `class` objects leads to *undefined behavior* - `memcpy` does not "understand" how C++ `class` works – UnholySheep Jul 25 '17 at 13:46
  • won't this not compile as you don't correctly return a new instance of `Class A` in your copy constructor – EdChum Jul 25 '17 at 13:46
  • @UnholySheep - Eh, standard layout types without pointers into themselves should be fine. – StoryTeller - Unslander Monica Jul 25 '17 at 13:49
  • If you hat initialized a and a1 correctly you simply could assign it `*a1 = *a`. –  Jul 25 '17 at 13:50
  • 1
    What you call a "custom copy operator" is actually a Copy Constructor. It is only used when copying an *object*. [`memcpy`](http://en.cppreference.com/w/cpp/string/byte/memcpy) copies an object's *representation* (underlying memory pattern), not the object. The copy constructor is not called when you use `memcpy`. In fact, no constructor, operator or object method is called at all. `memcpy` *only* copies the underlying memory pattern, which inevitably leads to undefined behavior unless the object being copied is [POD](http://en.cppreference.com/w/cpp/concept/PODType) (plain old data). – François Andrieux Jul 25 '17 at 13:52
  • @StoryTeller oh, right (the presence of the constructors confused me). But IMO that should be treated as a special case/exception (and therefore only be used by experienced programmers and when there is really a need for it). – UnholySheep Jul 25 '17 at 13:55
  • @UnholySheep - With that I agree wholeheartedly. There most definitely should be a mountain of static asserts on various traits whenever this is used. – StoryTeller - Unslander Monica Jul 25 '17 at 13:57
  • @EdChum Constructors don't return anything. `*this` is the object being constructed – molbdnilo Jul 25 '17 at 14:11
  • @EdChum I've fixed bug in my code, thanks! – Stefan.L Jul 25 '17 at 16:06
  • @Someprogrammerdude Sorry about that, i've made my code clean now. Thanks. – Stefan.L Jul 25 '17 at 16:07
  • @MichaelWalz added more about that, thanks for your help!! – Stefan.L Jul 25 '17 at 16:07
  • @StoryTeller Yeah, when i get the chance, i'll do, currently have to try code for it asap. Thanks for your comment! – Stefan.L Jul 25 '17 at 16:09
  • @UnholySheep So what's the best way to treat my situation(just added in question). Thanks! – Stefan.L Jul 25 '17 at 16:09
  • @FrançoisAndrieux I'm thinking class A object is not a POD, right? – Stefan.L Jul 25 '17 at 16:11

1 Answers1

0

Got a better understanding now, thanks you guys. I worked out to fix my trouble. And yes, trivial-featured POD ensures memcpy valid. Planning to grab a c++ book whenever get the chance, it could help a lot. Thanks!

Not sure why I can not submit this as the answer!!

This is the first time I ask questions here!

Stefan

Stefan.L
  • 1
  • 1