As I said in the comment.
Yes there is no problem with constructing from an archive.
(Another alternative is to have static load
function but that can have performance penalties).
The only potential problem I see with your approach is that your constructor can take almost anything as an argument and that can create problems.
And that can interfere with the copy constructor and other single argument constructors relying in implicit conversion.
So one has to restrict to take archives only.
There are different methods to do this, but based in this conversation http://marc.info/?l=boost&m=121131260728308&w=2, and by the fact that the inheritance tree of the archives
is documented http://www.boost.org/doc/libs/1_35_0/libs/serialization/doc/class_diagram.html, I think this is the best solution is to check that the argument derives from basic_iarchive
.
#include<type_traits>
struct Foo {
...
std::vector<int> data;
Foo() {
// populate "data" by doing calculation
data.push_back(1); data.push_back(2);
}
template<class IArchive,
typename = std::enable_if_t<std::is_base_of<boost::archive::detail::basic_iarchive, IArchive>::value>>
Foo( IArchive & ar ) {
ar >> data;
// populate "data" by reading the archive
}
...
};
int main(int argc, const char *argv[])
{
// deserialize
boost::archive::text_iarchive iar(std::cin);
Foo foo(iar); // will also work with other archives
}
As for what happens when your data is not default constructive see the discussion above.
Foo( Archive & ar ) : data(something) {
or have a level of indirection asFoot(Archive & ar) : data(somefunction(ar)){
(but something is smelly in the first place). – SusiVector LineSegment::direction()
wouldn't make sense (what is the direction from a point to the same point?) This is just a trivial example class so no use dwelling on it, but I think it makes the point that sometimes an object (in this case, a representation of a physical thing) doesn't make sense unless it is initialized with meaningful values, and it seems to make sense to differentiate between "this valid object is meaningful" and "this other valid object is nonsense". – Rochetteserialization
library. I always found "excuses" for not having a default constructor, and at the end they create more problems than what they solve. You have to deal with the problem of underfineddirection()
in any case, regardless of which is the default object. Of course if you consider "an emptyLineSegement
is not a valid segment" then it cannot be the default. However this opens a can of worms because your LineSegment space is not going to be a vector space. – Susi