假设我们有以下代码。我们有以下课程
_
class Animal
{
public:
Animal();
void HasWings() = 0;
};
class Bird : public Animal
{
public:
Bird() : Animal() {}
void HasWings() override { return true; }
};
class Dog : public Animal
{
public:
Dog() : Animal() {}
void HasWings() override { return false; }
};
class Zoo
{
public:
Zoo() {}
void AddAnimal(Animal* animal) { _animals.push_back(animal); }
...
std::vector<Animal*> _animals;
};
void myTest()
{
Zoo myZoo;
Bird* bird = new Bird();
Dog* dog = new Dog();
myZoo.AddAnimal(bird);
myZoo.AddAnimal(dog);
for (auto animal : myZoo._animals)
{
...
}
...
}我希望用智能指针的向量代替指针向量。也就是说,
std::vector<std::shared_ptr<Animal>> _animals;我们如何更改动物园和myTest的代码?我发现很难更新代码,尤其是Zoo类中的"AddAnimal“方法。
auto bird = std::make_shared<Bird>();
auto dog = std::make_shared<Dog>();
myZoo.AddAnimal(bird);
myZoo.AddAnimal(dog);鸟和狗是不同的类型。
发布于 2015-02-26 02:33:03
std::shared_ptr的行为非常类似于*和->运算符的原始指针(实际上,取消引用操作符被“转发”到由std::shared_ptr存储的内部原始指针)。特别是,您可以使用std::shared_ptr对基类进行类层次结构的虚拟分配。例如,下面的代码完全按照假设执行,即在运行时调用适当的函数:
#include <iostream>
#include <memory>
#include <vector>
struct Base
{
virtual void f() { std::cout << "Base::f()" << std::endl;}
virtual ~Base() = default; // to silence -Wall warnings
};
struct Derived: Base
{
void f() override { std::cout << "Derived::f()" << std::endl;}
};
int main()
{
std::vector<std::shared_ptr<Base>> vsp; // access Derived via shared_ptr to Base
auto base = std::make_shared<Base>();
auto derived = std::make_shared<Derived>();
vsp.push_back(base);
vsp.push_back(derived);
for(auto&& elem: vsp)
elem->f(); // virtual dispatch
}因此,在大多数情况下,用Animal*替换std::shared_ptr<Animal>就足够了,而且代码将只起作用。对于std::unique_ptr,事情要复杂一些,因为后者是只移动的类型(您不能复制它),所以必须更加小心。
https://stackoverflow.com/questions/28733385
复制相似问题