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