How can boost::serialization be used with std::shared_ptr from C++11?

后端 未结 7 1902
礼貌的吻别
礼貌的吻别 2020-12-08 20:23

I know that there is a Boost module for serialization of boost::shared_ptr, but I cannot find anything for std::shared_ptr.

Also, I don\'t know how to implement it e

7条回答
  •  孤街浪徒
    2020-12-08 20:38

    You haven't said what "doesn't work" means; it doesn't compile? It doesn't load/store the value properly? It doesn't..what?

    There are two problems I can identify here, one may be part of your intentional design though.

    The first, you have not made a correct pointer in the load procedure. Let's break it down:

    inline void serialize(Archive & ar, std::shared_ptr &t, const unsigned int version) {
        if (1) { //unimportant
            T* r;
            ar >> r;
            t = r;
        }
    }
    

    When you make an object of std::shared_ptr, you are instantiating a class template to provide pointer-like capability (as you know). If you made with an int, it will work as an int pointer. However, simply passing the type as T does NOT mean a pointer created of that type will automatically use that template; indeed, you're creating a bare pointer with T* r. It may as well be int *r. You then fail to initialize it with new; r could be pointing anywhere. If it were intialized properly with a new, you MAY get correct reference counting for creation/deletion of that object; this is one area where std::shared_ptr doesn't seem worth the effort to me. I think the assignment from a bare pointer counts as the second reference, not the first, but I may be wrong? Anyhow, that's not the problem. You're probably corrupting the heap; a compiler should spit out a warning about using an uninitialized pointer, it's a wonder it hasn't. I hope you don't have warnings turned off.

    If I remember correctly, that declaration of r needs to be replaced with:

    std::shared_ptr r = new std::shared_ptr;
    

    Although it may be

    std::shared_ptr r = new std::shared_ptr(r());
    

    I haven't used shared_ptr for a while.

    TR1, by the way, has been out for at least 2 years. It is based off of boost's shared_ptr. I don't know why you're using Boost 1.46, but I think that it was out by the time shared_ptr became part of the standard? So it should be compatible...?

    Anyhow, the second potential error comes with

    t = r;
    

    I'm assuming - incorrectly? - that you WISH to decrement the reference count to t by reassigning it (and possibly destroying the object t points to). If you meant to copy it, you would of course use:

    *t = *r;
    

    and make sure your copy constructor works properly.

提交回复
热议问题