2017-07-25 33 views
-5

正如我所瞭解的,在C++中,使用類對象執行memcpy將需要自定義複製構造函數,以使操作像memcpy有效。我錯了嗎?也沒有涉及的虛擬類方法,如下所示:在C++中,類實例對象做memcpy總是崩潰

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; 
} 

是否出現了一些錯誤?

此外,如果可能的話,請使用類對象更好地理解C++中的memcpy。非常感謝你。

++ 謝謝大家,我只是再次測試似乎我錯誤地瞭解memcpy和複製構造函數。在從另一個進程接收對象後使用memcpy來轉換爲類A的原因。那麼在這種情況下編碼的最佳方式是什麼? BR。 Stefan

+2

任何不爲了避免使用'memcpy'而定義拷貝構造函數的原因?也不知道你爲什麼要將一個'A *'投射到'uint64_t *' – EdChum

+1

這完全錯了!你初始化'a'指向*字符串*(不是實際的''A'對象)。您完全無視複製構造函數或複製分配來覆蓋數據。 –

+1

您的代碼不完整,您發佈的部分有誤。請發佈真實的代碼。 –

回答

0

現在有了更好的理解,謝謝你們。我努力解決我的麻煩。是的,功能簡單的POD確保memcpy有效。計劃抓住一本C++書籍,只要有機會,它可以幫助很多。謝謝!

不知道爲什麼我不能提交這個答案!

這是我第一次在這裏問問題!

Stefan