Using a vector of unique pointers to an <Employee> vector
Asked Answered
M

1

15

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

Mathieu answered 1/3, 2014 at 21:10 Comment(1)
Possible duplicate of Why can I not push_back a unique_ptr into a vector?Notochord
N
30

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).

Nineteenth answered 1/3, 2014 at 21:11 Comment(3)
you can also use EmpVect.emplace_back( TempEmp )Pruinose
@DaliborFrivaldsky You can? Pretty sure you'd still need to std::move it.Nineteenth
yes, you are right, it needs to be EmpVect.emplace_back( std::move(TempEmp) )Pruinose

© 2022 - 2024 — McMap. All rights reserved.