Re: class memory layout and portability

Discussion in 'C++' started by Shane Beasley, Jul 7, 2003.

  1. "Marco Jez" <marcojez@__NOSPAM__hotmail.com> wrote in message news:<beaaal$7qa$>...

    > Let's say we have the following structures (suppose that Struct_A is defined
    > too):
    >
    > struct Struct_A;
    >
    > struct Struct_B {
    > Struct_A my_object;
    > void do_something_on_object(); // read and/or write some fields of
    > my_object
    > };
    >
    > Can I assert that instances of Struct_B will have the same memory layout and
    > size as Struct_A? So, is it safe/portable to do things like:
    >
    > Struct_A *obj_a = new Struct_A(.....);
    > Struct_B *obj_b = reinterpret_cast<Struct_B *>(obj_a);
    > obj_b->do_something_on_object();


    If Struct_B is defined as above, then it is a POD struct, and the
    address of an instance of a POD struct is convertible to the address
    of its first data member[1] -- in other words, this code is fine.

    If Struct_B is not a POD struct, then whether your code works is
    defined by the implementation, not the Standard, meaning that it's not
    necessarily portable. A portable alternative in this case is to have a
    member function which returns a pointer/reference to the Struct_A data
    member.

    > What I'm trying to do is to enhance existing C-style structures by providing
    > a C++ interface around them, without creating new concrete data types by
    > encapsulation.


    You could also inherit Struct_B from Struct_A, in which case
    static_cast would do the job, too. Whether this is a good idea depends
    mostly on how tightly you want your C++ API to couple with the C one.

    - Shane

    ---
    1. <http://www.everything2.com/index.pl?node_id=1245318> has a nice
    little summary of what POD is and what it affords you, including
    references to the Standard.
    Shane Beasley, Jul 7, 2003
    #1
    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. Rick Spiewak
    Replies:
    3
    Views:
    3,131
    Rick Spiewak
    Aug 26, 2003
  2. RobertH
    Replies:
    1
    Views:
    708
    Steve C. Orr [MVP, MCSD]
    Nov 4, 2003
  3. NWx
    Replies:
    4
    Views:
    2,950
    Kevin Spencer
    Feb 19, 2004
  4. Gianni Mariani

    Re: class memory layout and portability

    Gianni Mariani, Jul 7, 2003, in forum: C++
    Replies:
    2
    Views:
    487
    Gianni Mariani
    Jul 7, 2003
  5. Replies:
    1
    Views:
    562
    John Timney \(MVP\)
    Jun 19, 2006
Loading...

Share This Page