Question

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

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top