0

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?

4

2 回答 2

4

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

vectorPolynomial.emplace_back(std::move(result));
于 2013-04-15T19:31:14.790 回答
1

虽然本杰明对您的代码的修改有效,但我觉得它有点倒退。毕竟,unique_ptr没有一个拷贝构造函数是有充分理由的;您的代码可以受益于使用普通对象而不是指针:

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

在这里,我们仅在实际需要时才手动分配内存,而不是更早。

于 2013-04-15T19:37:15.757 回答