Using a vector of unique pointers to an <Employee> vector

23,791

Calling push_back like that will attempt to copy the unique_ptr into the vector. You can't copy unique_ptrs! Instead, you need to move it into the vector:

EmpVect.push_back(std::move(TempEmp));

You do, however, have another problem. Your unique_ptr is not initialised to point at any particular allocated Employee, yet you then try to assign to that object. That's not good. Instead, you should dynamically allocate the Employee and pass it to the unique_ptr constructor:

unique_ptr<Employee> TempEmp(new Employee());

Or preferably, use an implementation of std::make_unique (which will be available in C++14).

Share:
23,791
CGutz
Author by

CGutz

Student working on BA in Computer Science

Updated on March 02, 2020

Comments

  • CGutz
    CGutz about 4 years

    For a school assignment, I am trying to use a vector of unique pointer's to Employee objects to access the Employee data, but can't figure out the syntax/compiler errors. Can anybody please tell me what I am doing wrong? Have to use a vector of smart pointers in this fashion.

    Here is the applicable code:

    // Create an Employee
    Employee EmpRec;
    
    // Assign value to a uniqueptr
    unique_ptr<Employee> TempEmp;
    *TempEmp = EmpRec;
    
    // Create a vector of unique_ptr<Employee>
    vector<unique_ptr<Employee>> EmpVect;
    
    // Push the TempEmp pointer onto the vector
    EmpVect.push_back(TempEmp);
    
    // Iterate through vector, calling display function 
    //that prints the values of various data inside the Employee object
    for (size_t i = 0; i < EmpVect.size(); ++i){
        (EmpVect[i])->display(cout);
    }
    

    This is how my Display function is defined:

    void display(std::ostream& cout) const{
        // print data members using cout <<
    }
    

    When trying to compile this, I get the following error:

    d:\microsoft visual studio 12.0\vc\include\xmemory0(593): error C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function

  • Dalibor Frivaldsky
    Dalibor Frivaldsky about 10 years
    you can also use EmpVect.emplace_back( TempEmp )
  • Joseph Mansfield
    Joseph Mansfield about 10 years
    @DaliborFrivaldsky You can? Pretty sure you'd still need to std::move it.
  • Dalibor Frivaldsky
    Dalibor Frivaldsky about 10 years
    yes, you are right, it needs to be EmpVect.emplace_back( std::move(TempEmp) )