6
我有四個類別(A
,B
,C
和D
)遵循經典菱形圖案和Container
類別包含unique_ptr<A>
。我想使用cereal序列化庫來序列化這些類。虛擬繼承和多態:穀物庫是否與對象佈局搞混了?
struct A {int f1; int f2; int f3}
struct B : public virtual A {
template<typename Archive>
inline void save(Archive& ar) const {
std::cerr << "Saving Obj: " << this << std::endl;
std::cerr << "This: " << &(this->f1) << " "
<< &(this->f2) << " " << &(this->f3) << std::endl;
std::cerr << "This: " << this->f1 << " "
<< this->f2 << " " << this->f3 << std::endl;
};
}
};
struct C : public virtual A {};
struct D : public B, public C {};
#include <cereal/archives/binary.hpp>
CEREAL_REGISTER_TYPE(B);
CEREAL_REGISTER_TYPE(C);
CEREAL_REGISTER_TYPE(D);
struct Container {
std::unique_ptr<A> obj;
template<typename Archive>
inline void save(Archive& ar) const {
std::cerr << "Saving Container" << std::endl;
std::cerr << "Obj Addr: " << obj.get() << std::endl;
std::cerr << "Obj: " << &(obj->f1) << " " << &(obj->f2)
<< " " << &(pq->f3) << std::endl;
std::cerr << "Obj: " << " " << pq->sq_count << " " << pq->sq_bits
<< " " << pq->dim << std::endl;
ar(obj); // Call serialization for obj, ie B.save(...)
}
}
類都穀物save
和load
功能,但我只包括他們B
和Container
,因爲他們在這個例子中使用的唯一的人。
我使用這些類如下:
std::unique_ptr<A> obj(new B);
obj->f1 = 8;
obj->f2 = 8;
obj->f3 = 128;
std::unique_ptr<Container> db(new Container);
db.obj = std::move(obj);
std::ofstream out_file(out_filename);
cereal::BinaryOutputArchive out_archive(out_file);
out_archive(db);
而且我得到以下輸出:
Saving Container
Obj Addr: 0x23d2128
Obj: 0x23d2130 0x23d2134 0x23d2138 // Fields adresses (f1,f2,f3)
Obj: 8 8 128 // Fields values
Saving Obj: 0x23d2128 // Same object
This: 0x23d2118 0x23d211c 0x23d2120 // Different field adresses !
This: 4293296 0 37569440 // Garbage
我的問題是:是否有可能,這是穀物中的錯誤,或者是有我沒有得到虛擬繼承的東西?
預計給定對象的字段地址是否會在C++程序中發生變化?
爲什麼'ar(obj)'調用'B :: save(ar)'? – aschepler
@aschepler穀類圖書館做到這一點:http://uscilab.github.io/cereal/serialization_functions.html – Xion345
我的意思是,'obj'是一個'std :: unique_ptr ',並且派生類型最多的是* obj'是'A'。 'B'跳入哪裏? – aschepler