I find I still do an embarrassingly large number of things in c style, so I am now trying to embrace the new millennium by reducing my usage of raw pointers. I have a vector of unique_ptr<BaseClass>
, that each points to an object of a derived class. I am trying to get a nice way to refer to one of the objects of the derived class. At the moment, I do this by using the .get()
function and casting this to the derived class.
However, as I understand it, .get()
is mostly there to interface with legacy code that insists on raw pointers, and its use should be avoided. Having another pointer to an object within a unique_ptr
doesn't seem like great style if it can be avoided. Is there a way to get a reference to the derived class object, without using get? Or some other convenient way of handling the object?
Here is a simplified code example:
#include <iostream>
#include <vector>
class Fruit {
public:
double size = 0;
virtual ~Fruit() = default;
};
class Apple : public Fruit {
public:
bool hasLeaf = false;
};
void doAppleStuff(std::vector<std::unique_ptr<Fruit> > &apples) {
// assume we know that element [0] exists and it is definitely of type Apple
auto apple = static_cast<Apple *> (apples[0].get()); // is there a better option?
if (apple->hasLeaf) {
std::cout << "We can leaf now" << std::endl;
} else {
std::cout << "We are pitiably leafless" << std::endl;
}
}
int main() {
std::vector<std::unique_ptr<Fruit> > fruitVec;
auto apple = new Apple;
apple->hasLeaf = true;
std::unique_ptr<Fruit> applePt(apple);
fruitVec.push_back(std::move(applePt));
doAppleStuff(fruitVec);
return 0;
}
(I think that it's probably possible to shorten the main function with make_unique
from c++14).
Would it be good coding style to do something like this?
auto &apple = *static_cast<Apple *> (apples[0].get());
The answer at "Downcasting" unique_ptr<Base> to unique_ptr<Derived> outlines a method to "cast" the unique_ptr
by releasing it and recreating a new unique_ptr
to the derived class, but that doesn't seem applicable here, as I don't really want to mess with the vector of unique pointers (unless I am missing something).