jazzybazz
jazzybazz

Reputation: 1887

Pushing back a pointer into a vector c++

This is a follow up to Using vectors to store different objects inherited from the same parent class c++ but you don't need to read it to understand.

I have a polynomial class and another class that is a container class. In the container class there is a vector that holds pointers to polynomials. I have defined vectorPolynomial this way:

std::vector<std::unique_ptr<Polynomial>> vectorPolynomial;

In the polynomial class there is a binary operator that do an operation that takes two polynomials and returns the result which is a polynomial itself.

Before polymorphism the operator returned an object of type Polynomial and I just did this:

Polynomial polynomialresult = polynomial1 % polynomial2;
vectorPolynomial.push_back(polynomialresult);

Now since the vector is not a vector of polynomials anymore, this won't work. Here is what I tried:

std::unique_ptr<Polynomial> result(new Polynomial);
*result = *(vectorPolynomial[i]) % *(vectorPolynomial[j]);
vectorPolynomial.emplace_back(result);

This didn't work. I also tried:

Polynomial * result = new Polynomial;

instead of the unique_ptr but it didn't work either. push_back instead of emplace_back does not work either.

How is this typically done?

Upvotes: 0

Views: 1421

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545528

While Benjamin’s amendment to your code works I feel that it’s a bit backwards. After all, unique_ptr hasn’t got a copy constructor for a good reason; your code could benefit from using normal objects rather than pointers:

Polynomial polynomialresult = *vectorPolynomial[i] % *vectorPolynomial[j];
vectorPolynomial.emplace_back(new Polynomial(polynomialresult));

Here we manually allocate memory only when we actually need to, no sooner.

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

unique_ptr has no copy constructor. So you need to move it:

vectorPolynomial.emplace_back(std::move(result));

Upvotes: 4

Related Questions