Boost logo

Boost Users :

From: Robert Ramey (ramey_at_[hidden])
Date: 2005-09-08 10:44:14


signatureOK I see the problem now.

Let me re-state it to be sure we're on the same page.

The class Person has a const member _name. In C++ const members can only be set when an object is constructed. In order to make sure no object is created without a name, There is no default constructor. When the serialization library creates a new instance - that is when loading a pointer, the library uses the non-default constructor to initialize the const variable with the correct value. When restoring the contents of an instance of the class Person that already exists the const member is not set.

Which seems totally correct to me.

The real question here is what is the intent in setting the member variable _name as const? Standard C++ behavior for const members is that they
a) are only set when the instance is constructed.
b) cannot be changed thereafter.

Now if we do the following:

Person p("bob")
...
ar << p;
...
Person p1("anne");
...
ar >> p1;

What should p1 contain? If you want p1 to contain "anne", then leave your program as it is. If you want it to contain "bob" then:

a) remove the const from the member _name
b) implement the normal member serialization for _name.
c) at this point, loading pointers will result in _name being loaded twice. If this is a problem, you could
    i) add a default constructor and elminate the save/load construct data. You might want to make the default constructor private and include friend boost::serialization::access to your class. (I haven't tried this but I believe it should work.

An alternative to a) above would be to leave the "const" but use a const_cast inside the class serialization function.

At the heart of the matter here is the what we want const to mean. Should const variables never change during the life of the class? - then we expect p1 to contain "bob". Otherwise they are not really "const" in the traditional C++ sense and should be addressed by removing the const, or a cast or?

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