so I’m using the boost::serialization library, and I’m trying to overide how a class is constructed, since it has no default constructor. This is demonstrated here. To me it appears the function takes the class* t and then sets it to point to a newly constructed object. If i’m wrong, this is definately the source of my error.
However, the only way to construct my class is by using another classes create() function, meaning I need to stray from the code in the example (this is stated in the boost::serialization namespace): ::new(t)my_class(attribute);
I tried simply calling the create function and setting t equal to the returned pointer, but this doesn’t seem to work because right after the load_construct_data function, and in the serialization function, the given myClass& is not the same as what I set ‘t’ to.
How do I do whatever ::new(t) is doing so the object created using the create function follows through into the serialize/other functions?
The construct referred to in your question (
new(t) my_class(attribute)) is called “placement new”. The way it work is thattmust already point to an allocated region of memory (placement new doesn’t do allocation by default)my_classis constructed at that memory location.However, since in your case you can’t use constructors, then using any form of
newis out of the question. But there is an alternative (sort of).Since placement new pretty much just overwrites a chunk memory, we can use a regular function which does the same with an already constructed object. Such a function is
memcpy:All
memcpydoes is perform a byte-wise copy ofnumbytes from the memory pointed to bysourceto the memory pointed to bydestination.So let’s say you started with this code in the
load_construct_dataThen we can use the
memcpyfunction to “move” the value atobjinto the memory reference byt:While there are some details about how this works with your particular class, such as whether a bit-wise copy is “good enough”, this is the best I’ve got with what you’ve asked. The one problem I see is if the destructor releases resources, than the copy will may become invalid.
To account for the possible problems with destruction, you can write your own deep copying function:
which you call instead of
memcpy.Note: please tell me if I went astray with anything here. I don’t currently have a machine to test code on.