Best Way To Copy Complex Structs

Discussion in 'C++' started by mieskola, Nov 10, 2006.

  1. mieskola

    mieskola Guest

    Given the following struct definition:

    struct Data
    {
    int i;
    ComplexType c;
    };


    do either of the following copying methods have a programmatic
    advantage? Style?

    Data d;
    Data e;

    d.i = 4;
    ..
    ..
    ..


    METHOD 1: e = d;
    METHOD 2: memcpy(&e,&d, sizeof(d));
     
    mieskola, Nov 10, 2006
    #1
    1. Advertising

  2. mieskola

    Rolf Magnus Guest

    mieskola wrote:

    > Given the following struct definition:
    >
    > struct Data
    > {
    > int i;
    > ComplexType c;
    > };
    >
    >
    > do either of the following copying methods have a programmatic
    > advantage? Style?
    >
    > Data d;
    > Data e;
    >
    > d.i = 4;
    > .
    > .
    > .
    >
    >
    > METHOD 1: e = d;
    > METHOD 2: memcpy(&e,&d, sizeof(d));


    The second is only guaranteed to work if ComplexType is a POD. Method 1
    works for any assignable type. It's also easier to read.
     
    Rolf Magnus, Nov 10, 2006
    #2
    1. Advertising

  3. mieskola

    Guest

    Thanks Rolf. I much prefer method 1 myself.

    AJ


    Rolf Magnus wrote:
    > mieskola wrote:
    >
    > > Given the following struct definition:
    > >
    > > struct Data
    > > {
    > > int i;
    > > ComplexType c;
    > > };
    > >
    > >
    > > do either of the following copying methods have a programmatic
    > > advantage? Style?
    > >
    > > Data d;
    > > Data e;
    > >
    > > d.i = 4;
    > > .
    > > .
    > > .
    > >
    > >
    > > METHOD 1: e = d;
    > > METHOD 2: memcpy(&e,&d, sizeof(d));

    >
    > The second is only guaranteed to work if ComplexType is a POD. Method 1
    > works for any assignable type. It's also easier to read.
     
    , Nov 10, 2006
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Patricia  Van Hise

    structs with fields that are structs

    Patricia Van Hise, Apr 5, 2004, in forum: C Programming
    Replies:
    5
    Views:
    646
    Al Bowers
    Apr 5, 2004
  2. Chris Hauxwell

    const structs in other structs

    Chris Hauxwell, Apr 23, 2004, in forum: C Programming
    Replies:
    6
    Views:
    561
    Chris Hauxwell
    Apr 27, 2004
  3. Paminu
    Replies:
    5
    Views:
    647
    Eric Sosman
    Oct 11, 2005
  4. Daniel Rudy
    Replies:
    15
    Views:
    1,411
    Keith Thompson
    Apr 10, 2006
  5. rdc02271
    Replies:
    24
    Views:
    744
    Jacek Dziedzic
    Dec 27, 2005
Loading...

Share This Page