提升(反)序列化派生对象的向量,使用删除函数(unique_ptr)

Boost (de)serialize vector of dervied objects, use of deleted finction (unique_ptr)

我正在尝试在我的项目中实现序列化。我的问题是,当我尝试反序列化对象时,出现如下错误:

/usr/include/c++/5/ext/new_allocator.h:120:4: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Employee; _Dp = std::default_delete<Employee>]’
  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

编辑:我添加了 hireInternemployeeMenu 函数并减少了一些不必要的代码。

class Employee {  
protected:    
    int employeeID;
    std::string Name;
    std::string Surname;
    int Salary;
    bool Hired;   
public:   
    friend class boost::serialization::access;

    template<typename Archive>
    void serialize(Archive & ar, const unsigned int file_version) {
        ar & employeeID;
        ar & Name;
        ar & Surname;
        ar & Salary;
        ar & Hired;

    }    
    virtual ~Employee();
    Employee();
    Employee(const std::string &, const std::string &);

.cpp

#include "Employee.h"   
Employee::~Employee() = default;    
Employee::Employee() = default;   
Employee::Employee(const std::string &newName, const std::string &newSurname) : Name(newName), Surname(newSurname) {}

派生,"Intern.h"

class Intern : public Employee {
public:
    friend class boost::serialization::access;

    template<typename Archive>
    void serialize(Archive & ar, const unsigned int file_version) {
        ar & boost::serialization::base_object<Employee>(*this);
        ar & Status;
    }

    std::string Status = "Intern";

    Intern();
    ~Intern();
    Intern(const std::string &, const std::string &);

};
BOOST_CLASS_EXPORT_KEY(Intern);

.cpp

#include "Intern.h"   
BOOST_CLASS_EXPORT_IMPLEMENT(Intern);    
Intern::Intern() = default;   
Intern::~Intern() = default;    
Intern::Intern(const std::string &newName, const std::string &newSurname) : Employee(newName, newSurname) {}

开头的注释行导致反序列化错误。 当我忽略它们时,在 case 3: 中实现的序列化工作正常。 问题是,我还想在开始时将对象从 .txt 文件加载到向量中。

void mainMenu() {

    //std::ifstream ifs("database");
    //boost::archive::text_iarchive ia(ifs);

    vector<unique_ptr<Employee>> Firm;

    //ia >> boost::serialization::make_nvp("root", Firm);
...

        switch (option) {
            case 1:
                hireIntern(Firm);
                break;
            case 2:
                employeeMenu(Firm);
                break;
            case 3:
            {
                std::ofstream ofs("database");
                boost::archive::text_oarchive oa(ofs);
                oa << boost::serialization::make_nvp("root", Firm);

                return;
            }
...

.

void hireIntern(vector<unique_ptr<Employee>>& sourceEmployee) {
    ...
        sourceEmployee.emplace_back(new Intern(fillName, fillSurname));

。在 employeeMenu 中调用的函数中,我只是编辑一些 Firm 对象字段向量,例如 sourceEmployee[index]->setSalary(sourceEmployee[index]->getSalary() + 1000);

  void employeeMenu(vector<unique_ptr<Employee>>& sourceEmployee) {

...

        switch (option) {

            case 1:
                Promote(sourceEmployee);
                break;
            case 2:
                Demote(sourceEmployee);
                break;
            case 3:
                fireEmployee(sourceEmployee);
                break;
            case 4:
                employeeShowcase(sourceEmployee);
                break;
            case 5:
                showHiredEmployees(sourceEmployee);
                break;
            case 6:
                showFiredEmployees(sourceEmployee);

当我用这些行编译代码时出现以下错误:

/usr/local/bin/cmake --build /home/max/c++/PROJEKT/cmake-build-debug --target PROJEKT -- -j 2
Scanning dependencies of target PROJEKT
[ 12%] Building CXX object CMakeFiles/PROJEKT.dir/mainMenu.cpp.o
In file included from /usr/include/x86_64-linux-gnu/c++/5/bits/c++allocator.h:33:0,
                 from /usr/include/c++/5/bits/allocator.h:46,
                 from /usr/include/c++/5/string:41,
                 from /usr/include/c++/5/bits/locale_classes.h:40,
                 from /usr/include/c++/5/bits/ios_base.h:41,
                 from /usr/include/c++/5/ios:42,
                 from /usr/include/c++/5/istream:38,
                 from /usr/include/c++/5/fstream:38,
                 from /home/max/c++/PROJEKT/Employee.h:8,
                 from /home/max/c++/PROJEKT/manageDatabase.h:8,
                 from /home/max/c++/PROJEKT/mainMenu.cpp:5:
/usr/include/c++/5/ext/new_allocator.h: In instantiation of ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = std::unique_ptr<Employee>; _Args = {const std::unique_ptr<Employee, std::default_delete<Employee> >&}; _Tp = std::unique_ptr<Employee>]’:
/usr/include/c++/5/bits/alloc_traits.h:530:4:   required from ‘static void std::allocator_traits<std::allocator<_CharT> >::construct(std::allocator_traits<std::allocator<_CharT> >::allocator_type&, _Up*, _Args&& ...) [with _Up = std::unique_ptr<Employee>; _Args = {const std::unique_ptr<Employee, std::default_delete<Employee> >&}; _Tp = std::unique_ptr<Employee>; std::allocator_traits<std::allocator<_CharT> >::allocator_type = std::allocator<std::unique_ptr<Employee> >]’
/usr/include/c++/5/bits/stl_vector.h:917:30:   required from ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<Employee>; _Alloc = std::allocator<std::unique_ptr<Employee> >; std::vector<_Tp, _Alloc>::value_type = std::unique_ptr<Employee>]’
/usr/local/include/boost/serialization/vector.hpp:102:13:   required from ‘void boost::serialization::load(Archive&, std::vector<U, Allocator>&, unsigned int, mpl_::false_) [with Archive = boost::archive::text_iarchive; U = std::unique_ptr<Employee>; Allocator = std::allocator<std::unique_ptr<Employee> >; mpl_::false_ = mpl_::bool_<false>]’
/usr/local/include/boost/serialization/vector.hpp:173:9:   required from ‘void boost::serialization::load(Archive&, std::vector<U, Allocator>&, unsigned int) [with Archive = boost::archive::text_iarchive; U = std::unique_ptr<Employee>; Allocator = std::allocator<std::unique_ptr<Employee> >]’
/usr/local/include/boost/serialization/split_free.hpp:58:13:   required from ‘static void boost::serialization::free_loader<Archive, T>::invoke(Archive&, T&, unsigned int) [with Archive = boost::archive::text_iarchive; T = std::vector<std::unique_ptr<Employee> >]’
/usr/local/include/boost/serialization/split_free.hpp:74:18:   [ skipping 22 instantiation contexts, use -ftemplate-backtrace-limit=0 to disable ]
/usr/local/include/boost/archive/detail/iserializer.hpp:618:18:   required from ‘void boost::archive::load(Archive&, T&) [with Archive = boost::archive::text_iarchive; T = const boost::serialization::nvp<std::vector<std::unique_ptr<Employee> > >]’
/usr/local/include/boost/archive/detail/common_iarchive.hpp:66:22:   required from ‘void boost::archive::detail::common_iarchive<Archive>::load_override(T&, int) [with T = const boost::serialization::nvp<std::vector<std::unique_ptr<Employee> > >; Archive = boost::archive::text_iarchive]’
/usr/local/include/boost/archive/basic_text_iarchive.hpp:71:9:   required from ‘void boost::archive::basic_text_iarchive<Archive>::load_override(T&, int) [with T = const boost::serialization::nvp<std::vector<std::unique_ptr<Employee> > >; Archive = boost::archive::text_iarchive]’
/usr/local/include/boost/archive/text_iarchive.hpp:92:52:   required from ‘void boost::archive::text_iarchive_impl<Archive>::load_override(T&, int) [with T = const boost::serialization::nvp<std::vector<std::unique_ptr<Employee> > >; Archive = boost::archive::text_iarchive]’
/usr/local/include/boost/archive/detail/interface_iarchive.hpp:60:9:   required from ‘Archive& boost::archive::detail::interface_iarchive<Archive>::operator>>(T&) [with T = const boost::serialization::nvp<std::vector<std::unique_ptr<Employee> > >; Archive = boost::archive::text_iarchive]’
/home/max/c++/PROJEKT/mainMenu.cpp:16:54:   required from here
/usr/include/c++/5/ext/new_allocator.h:120:4: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Employee; _Dp = std::default_delete<Employee>]’
  { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
    ^
In file included from /usr/include/c++/5/bits/locale_conv.h:41:0,
                 from /usr/include/c++/5/locale:43,
                 from /usr/include/c++/5/iomanip:43,
                 from /usr/local/include/boost/archive/basic_text_oprimitive.hpp:27,
                 from /usr/local/include/boost/archive/text_oarchive.hpp:30,
                 from /home/max/c++/PROJEKT/Employee.h:9,
                 from /home/max/c++/PROJEKT/manageDatabase.h:8,
                 from /home/max/c++/PROJEKT/mainMenu.cpp:5:
/usr/include/c++/5/bits/unique_ptr.h:356:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^
CMakeFiles/PROJEKT.dir/build.make:114: recipe for target 'CMakeFiles/PROJEKT.dir/mainMenu.cpp.o' failed
make[3]: *** [CMakeFiles/PROJEKT.dir/mainMenu.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/PROJEKT.dir/all' failed
make[2]: *** [CMakeFiles/PROJEKT.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/PROJEKT.dir/rule' failed
make[1]: *** [CMakeFiles/PROJEKT.dir/rule] Error 2
Makefile:118: recipe for target 'PROJEKT' failed
make: *** [PROJEKT] Error 2

我认为在您的情况下您应该使用 shared_ptr 而不是 unique_ptr,因为您在 main 函数、std::vector 容器之间共享指针所有权, hireIntern 函数、employeeMenu 函数以及 boost::serialization 例程。 unique_ptr 只应在当时只有一个 unique_ptr 实例指向同一内存时使用 - 即它具有唯一的所有权。如果您坚持对容器使用 unique_ptr 并且希望将该容器传递给函数,请阅读 this question 以了解如何使用移动语义(因为 unique_ptr 的复制构造函数已被删除)。否则,我推荐 shared_ptr.

根据您的评论编辑 ====

在您提供的堆栈跟踪中,您可以找到:

/usr/include/c++/5/bits/stl_vector.h:917:30:   required from ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<Employee>; _Alloc = std::allocator<std::unique_ptr<Employee> >; std::vector<_Tp, _Alloc>::value_type = std::unique_ptr<Employee>]’
/usr/local/include/boost/serialization/vector.hpp:102:13:   required from ‘void boost::serialization::load(Archive&, std::vector<U, Allocator>&, unsigned int, mpl_::false_) [with Archive = boost::archive::text_iarchive; U = std::unique_ptr<Employee>; Allocator = std::allocator<std::unique_ptr<Employee> >; mpl_::false_ = mpl_::bool_<false>]’

您可以看到您使用类型 std::vector<std::unique_ptr<Employee>, "standard allocator"> 实例化的 boost::serialization 例程正在尝试执行 void std::vector<_Tp, _Alloc>::push_back(const value_type&),这对于类型 std::unique_ptr 是严格禁止的。我猜这个问题出现在 text_iarchive 实例化时——顾名思义它是一个输入 class 并且它可能在某个时候调用 push_back (它很容易被确认,只需快速扫描提升代码).

因此,如果您打算在容器中存储智能指针,这通常意味着您真的不想为此目的使用 std::unique_ptr