Results 1 to 2 of 2

Thread: Copying object with memcpy

  1. #1
    Join Date
    Jan 2009
    Location
    Germany
    Posts
    387
    Thanks
    101
    Thanked 15 Times in 15 Posts
    Qt products
    Qt4 Qt5
    Platforms
    Unix/X11 Windows

    Default Copying object with memcpy

    When writing a custom assignment operator, is there a caveat to first copying the whole object with a memcpy rather than tediously field by field, and then fixing the pointers and such? This is what I mean:

    Qt Code:
    1. MyObject& MyObject::operator=(const MyObject &o)
    2. {
    3. memcpy(this, &o, sizeof(MyObject)); // Copy everything in one go.
    4.  
    5. // Do other things like fix pointers.
    6.  
    7. return *this;
    8. }
    To copy to clipboard, switch view to plain text mode 

  2. #2
    Join Date
    Dec 2009
    Location
    New Orleans, Louisiana
    Posts
    791
    Thanks
    13
    Thanked 153 Times in 150 Posts
    Qt products
    Qt5
    Platforms
    MacOS X

    Default Re: Copying object with memcpy

    I'd say if MyObject is a class you designed and understand the implications of doing so, then go for it. However, if you don't know the internals of the MyObject class and what affects this would have, I'd advise against it.
    I write the best type of code possible, code that I want to write, not code that someone tells me to write!

Similar Threads

  1. Unable to memcpy a buffer to a struct
    By kiboi in forum General Programming
    Replies: 4
    Last Post: 17th November 2012, 02:22
  2. Replies: 11
    Last Post: 3rd April 2012, 04:51
  3. memcpy not working properly
    By sattu in forum Qt Programming
    Replies: 3
    Last Post: 26th October 2010, 23:33
  4. problem with memcpy
    By sattu in forum General Programming
    Replies: 16
    Last Post: 29th September 2010, 09:20
  5. Save 4 Integers in a QByteArray without memcpy
    By GonzoFist in forum Newbie
    Replies: 3
    Last Post: 17th May 2010, 23:15

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.