Boost logo

Boost Users :

Subject: Re: [Boost-users] [Serialization] Non-default constructor and static data members
From: Robert Ramey (ramey_at_[hidden])
Date: 2015-06-04 15:13:21


On 6/4/15 9:38 AM, Mccall, Kurt E. (JSC-EG411) wrote:
> I'm trying to serialize a class with a non-default constructor and
> static const data members, so
> I have to override boost::serialization::save_construct_data() and
> load_construct_data(). I am
> getting a linking error:the static members referred to
> in save_construct_data() cannot be found
> ("undefined reference").
>
> #include <boost/archive/tmpdir.hpp>
> #include <boost/archive/xml_iarchive.hpp>
> #include <boost/archive/xml_oarchive.hpp>
>
> // forward declarations
> class A;
> namespace boost { namespace serialization {
> template<class Archive>
> inline void save_construct_data(Archive &ar, const A *t, const
> unsigned int file_version);
> } }
>
> class A {
> friend class boost::serialization::access;
>
> // friend function (omitting load_construct_data() for brevity)
> template<class Archive>
> friend void save_construct_data(Archive &ar, const A *t, const
> unsigned int file_version);
>
> public:
> static const int var1 = 1;
> static const int var2 = 2;
>
> template<class Archive>
> void serialize(Archive & ar, const unsigned int file_version)
> {
> // do nothing
> };
> }
>
> // overridden Boost function
> namespace boost { namespace serialization {
> template<class Archive>
> inline void save_construct_data(
> Archive &ar, const A *t, const unsigned int file_version)
> {
> // link errors happen at both of these two lines ("undefined
> reference" of var1, var2).
> ar << boost::serialization::make_nvp("var1", ::A::var1); // eliminate this
> ar << boost::serialization::make_nvp("var2", t->var2); // eliminate this - so might as well eliminate the whole function
> };
> }} // namespace…
>
> This puzzles me since I thought that static members have external
> linkage. This question seems
> to be more about namespaces than it is about Boost::Serialization, but I
> post here because some Serialization user must have run into it.

I'm not so sure about that. There no need to serialize the static const
values since they are fixed and initialized before the first instance is
constructed.

It has always been that static variables had to be explicitly
initialized outside the class. As in

const int A::var1 = 1; // no longer necessary
const int A::var2 = 2;

But I guess C++11 changed that.

Robert Ramey


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net