A third party library has structs defined as
typedef struct _Example
{
int member;
} Example;
As a side question, just out of interest, why that definition? Why not struct Example { ... }
?
Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just change my version of the 3rd party header file by adding a constructor to the struct definition? Or alternatively, to just copy that definition to my own code base, rename it, add a constructor, and reinterpret_cast to it?
I assume it would be because as I understand functions and constructors shouldn't change the underly开发者_如何学Pythoning byte layout of the class/struct, is this correct?
Thanks
It's better to derive from that struct and define all the constructors you need. Modifying third-party libraries and copy-pasting definitions is not a good idea.
typedef struct
pattern comes from C. In [older?] C, struct _Something
does not allow you to use _Something
as a type:
//_Something x;//not allowed
struct _Something x; //ok
With typedef, one can define variables in natural Something x
way, without that struct
burden.
The typedef struct ...
is derives from C
and not C++
to use shorthands for struct
s. Is it possible that the 3rd party library is written in C?
I wouldn't suggest using reinterpret_casts like you are trying. I suggest you create a small wrapper class to encapsulate the Example
struct. This is safer and can spare you a lot of debugging pain.
HTH
Your struct has a constructor. Compiler generated for you a no-arg constructor and thats exactly what boost::serialization needs.
Why not struct Example { ... } ?
struct Example {...};
is the way how you should define a struct
in C++, while the typedef
form is old C-style.
functions and constructors shouldn't change the underlying byte layout of the
class/struct
That depends. Functions are stored separated with your data in text section. So adding a normal function won't affect the size and layout of your struct
. However, if there is any virtual
functions, a "hidden" VPTR will be added in your class. Thus the layout could be very different from that w/o virtual functions.
Is it safe to just change my version of the 3rd party header file by adding a
constructor to the struct definition? Or alternatively, to just copy that definition
to my own code base, rename it, add a constructor, and reinterpret_cast to it?
I strongly recommend you not to copy the definition. That's a very bad idea, especially when that is 3rd-party class out of your control. What if they change its definition one day? There are several ways that you can handle it. E.g., either use aggregation or inheritance. Actually, in this case I think the use of aggregation excels.
// The layout of this struct is the same as
// that of struct Example
struct MyExample
{
Example m_ex;
MyExample(int member)
{
m_ex.member = member;
}
//..
};
精彩评论